@magicx-eng/ai-autocomplete-vanilla 0.33.0 → 0.35.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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- function it(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function U(t){let e=it(t);return e.length>0?e.join(" "):t}var te=["January","February","March","April","May","June","July","August","September","October","November","December"],ve=["S","M","T","W","T","F","S"],rn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],sn="aiaDate",an="aiaDay",nn=t=>String(t).padStart(2,"0");function k(t){return`${t.getFullYear()}-${nn(t.getMonth()+1)}-${nn(t.getDate())}`}function ot(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function Xi(t){let e=ot(t).getTime()-ot(new Date).getTime();return Math.round(e/864e5)}function ln(t){let e=Xi(t);return e>=0&&e<7?rn[t.getDay()]:ne(t)}function ne(t){return t.getFullYear()===new Date().getFullYear()?`${te[t.getMonth()]} ${t.getDate()}`:`${te[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function Ee(t){if(!t)return null;let e=rn.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=ot(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let n=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(t);if(!n)return null;let i=te.findIndex(a=>a.toLowerCase()===n[1].toLowerCase());if(i<0)return null;let o=Number(n[2]),r=n[3]?Number(n[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function rt(t){return`${te[t.month]} ${t.year}`}function st(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function dn(t){return{year:t.getFullYear(),month:t.getMonth()}}function at(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function on(){return{text:"",is_tappable:!1,kind:null}}function lt(t){let e=new Date(t.year,t.month,1).getDay(),n=new Date(t.year,t.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(on());for(let o=1;o<=n;o++){let r=new Date(t.year,t.month,o);i.push({text:ln(r),is_tappable:!0,kind:null,metadata:{[sn]:k(r),[an]:o}})}for(;i.length%ve.length!==0;)i.push(on());return i}function dt(t){let e=Ee(t);return e?k(e):null}function N(t){let e=t?.metadata?.[sn];return typeof e=="string"?e:null}function ct(t){let e=t?.metadata?.[an];return typeof e=="number"?e:null}function ji(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function cn(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:te.findIndex(n=>n.toLowerCase().startsWith(e))}function zi(t,e,n){let i=new Date(n.getFullYear(),t,e);if(i.getMonth()!==t||i.getDate()!==e)return null;let o=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(i>=o)return i;let r=new Date(n.getFullYear()+1,t,e);return r.getMonth()===t&&r.getDate()===e?r:null}function un(t,e,n){let i=new Date(t,e,n);return i.getMonth()===e&&i.getDate()===n?i:null}function K(t,e={}){if(!t)return null;let n=e.today??new Date,i=ji(t.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=un(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?k(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(r){let l=cn(r[1]);if(l>=0)return we(l,Number(r[2]),r[3],n)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=cn(s[2]);if(l>=0)return we(l,Number(s[1]),s[3],n)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),d=Number(a[2]);return l>12&&d<=12?we(d-1,l,a[3],n):d>12&&l<=12?we(l-1,d,a[3],n):null}return null}function we(t,e,n,i){if(n){if(n.length!==4)return null;let r=un(Number(n),t,e);return r?k(r):null}let o=zi(t,e,i);return o?k(o):null}function ut(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:K(t.text,e)}var mn=" - ",mt="aiaDateRangeStart",ft="aiaDateRangeEnd";function ce(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var pt=/^\d{4}-\d{2}-\d{2}$/;function pn(t){if(!pt.test(t))return null;let[e,n,i]=t.split("-").map(Number),o=new Date(e,n-1,i);return o.getMonth()===n-1&&o.getDate()===i?o:null}var Ji=/\s+(?:to|through|thru|until|til|till)\s+/g,Zi=/[-–—]/g;function eo(t){let e=[];for(let n of[Ji,Zi]){n.lastIndex=0;let i=n.exec(t);for(;i!==null;)e.push([t.slice(0,i.index),t.slice(i.index+i[0].length)]),i=n.exec(t)}return e}function ie(t,e={}){if(!t)return null;let n=new Set,i=null;for(let[o,r]of eo(t.trim())){let s=K(o.trim(),e);if(!s)continue;let a=K(r.trim(),e);!a||a<s||(n.add(`${s}|${a}`),i={start:s,end:a})}return n.size===1?i:null}function fn(t){let e=pn(t.start),n=pn(t.end);return!e||!n?"":t.start===t.end?ne(e):`${ne(e)}${mn}${ne(n)}`}function gn(t,e){let n=ce(t,e);return{text:fn(n),is_tappable:!0,kind:null,metadata:{[mt]:n.start,[ft]:n.end}}}function ue(t,e={}){let n=t?.metadata?.[mt],i=t?.metadata?.[ft];return typeof n=="string"&&typeof i=="string"&&pt.test(n)&&pt.test(i)?ce(n,i):ie(t?.text,e)}function w(t){return t==="date"||t==="date-range"}var to=new Set(["date","dates"]),no=new Set(["range","ranges","span","period","window"]),hn=3;function io(t){let e={single:0,range:0};if(!t)return e;for(let n of t)n.is_tappable&&(ie(n.text)!==null?e.range+=1:K(n.text)!==null&&(e.single+=1));return e}function Y(t){if(!t)return"options";let e=t.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let n=io(t.options);if(n.single+n.range>=hn&&n.range>n.single)return"date-range";let i=it(t.type);return i.some(o=>to.has(o))?i.some(o=>no.has(o))?"date-range":"date":n.single>=hn?"date":"options"}var Pe=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 oo="https://api.ai-autocomplete.com",Te=`${oo}/api/suggest`,bn=new WeakMap;function pe(t){return t?.type==="accessToken"}function ro(t){if(!(!t||pe(t)))return t}function Ce(t){let e=bn.get(t.getAccessToken);return e||(e=new Pe(t),bn.set(t.getAccessToken,e)),e}function Ie(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function Oe(t){let e=ro(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function me(t){return t.map(e=>({type:e.type,value:e.text}))}var yn="skipped";function fe(t,e){if(e.length===0)return t;let n=new Set(t.map(o=>o.type)),i=e.filter(o=>!n.has(o.type)).map(o=>({placeholder:"",type:o.type,text:yn,kind:null}));return i.length>0?[...t,...i]:t}var so="0.33.0",Sn=!1;function ao(t,e){return{placeholder:t.placeholder,type:t.type,...e&&{text:t.value??t.text},kind:t.kind}}function lo(t,e,n,i,o,r,s,a,l,d){let c=e.find(m=>m.type==="contact"&&m.metadata?.contact_account_count)?.metadata?.contact_account_count,u=typeof c=="number"?c:void 0;return{data:{raw_query:t,completed_params:fe(e.map(m=>ao(m,n)),l??[]),...s&&s.length>0&&{identified_params:me(s)},...a&&a.length>0&&{recently_suggested:a},...u!=null&&{contact_account_count:u},...d!==void 0&&{additional_context:d}},meta:{request_id:o,request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:so,session_id:i,source:r}}}async function xn(t,e,n,i,o){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:i,signal:o})}async function vn(t,e,n){let i=n.apiConfig,o=!n.maskCompletedText,r=lo(t,e,o,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext),s=Ie(i),a=i?.endpoint??Te,l=JSON.stringify(r);if(pe(i)){let u=Ce(i),m=await u.getToken(),f=await xn(a,s,m,l,n.signal);if(f.status===401){let g=await u.getToken(!0);f=await xn(a,s,g,l,n.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let d=Oe(i);!d&&!Sn&&(Sn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(s.Authorization=d);let c=await fetch(a,{method:"POST",headers:s,body:l,signal:n.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}var Ae=/[\p{L}\p{N}]/u,co=/['\u2019-]/;function En(t,e,n){let i=t[e];if(i===void 0)return!1;if(Ae.test(i))return!0;let o=t[e+n];return co.test(i)&&o!==void 0&&Ae.test(o)}function uo(t,e,n){let i=e+n.length;return!(Ae.test(n[0])&&En(t,e-1,-1)||Ae.test(n[n.length-1])&&En(t,i,1))}function F(t,e,n=0,i=()=>!0){if(e.length===0)return t.indexOf(e,n);let o=-1,r=t.indexOf(e,n);for(;r!==-1;){if(i(r)){if(uo(t,r,e))return r;o===-1&&(o=r)}r=t.indexOf(e,r+1)}return o}function R(t,e){let n=t,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=f=>F(n,a.text,f,g=>!r.some(S=>g<S.end&&g+a.text.length>S.start)),m=u(s);if(m===-1&&(m=u(0)),m!==-1){n=n.slice(0,m)+c+n.slice(m+a.text.length);let f=c.length-a.text.length;for(let g of r)g.start>=m+a.text.length&&(g.start+=f,g.end+=f);r.push({start:m,end:m+c.length}),s=m>=s?m+c.length:s+f}o.push({...a,placeholder:c})}return{rawQuery:n,completedParams:o}}function H(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function Re(t,e,n){return e===0&&t.length>0&&n.length>0&&n.toLowerCase().startsWith(t.toLowerCase())}function Q(t,e,n){let i=t.slice(e);if(n||e===0||t[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function wn(t,e){let n=t.trimEnd().replace(/\s+/g," ");if(n.length===0||e.length===0)return 0;let i=n.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=n.length-s.length;return t.length-a}}return 0}function X(t,e){if(!t)return[];let n=e.trimStart();if(!n)return t;let i=n.toLowerCase();return t.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function oe(t,e){if(!t)return null;let n=e.trim();if(!n)return null;let i=n.toLowerCase();return t.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function Pn(t,e){return e?t.map(n=>e[n.type]?{...n,options:[]}:n):t}function Tn(t,e){let n=0,i=e;for(let o of t)n+=o.value.length,o.type!=="text"&&(i=Math.max(i,n));return i}function Cn(t,e){let n=0;for(let i of t){let o=n+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-n,0)).trim().length>0)return!1;n=o}return!0}function In(t,e){let n=[],i=new Set;for(let o of[...t,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),n.push({type:o.type,text:o.text}));return n}function On(t,e,n){if(t===e)return n;let i=Math.min(t.length,e.length),o=0;for(;o<i&&t[o]===e[o];)o++;if(o>=n)return n;let r=0;for(;r<i-o&&t[t.length-1-r]===e[e.length-1-r];)r++;return t.length-r<=n?n+(e.length-t.length):null}function Le(t,e){let n=[],i=[],o=0;for(let r of e){let s=F(t,r.text,o);if(s===-1){i.push(r);continue}n.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:n,missing:i}}function An(t,e){let{located:n}=Le(t,e);return n.length>0?n[n.length-1].end:0}function Rn(t,e,n){let i=[],o=[],r=0;for(let s of n){let a=F(t,s.text,r,l=>!e.some(d=>l<d.end&&l+s.text.length>d.start));if(a===-1){o.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:i,missing:o}}function Ln(t,e,n=[]){let i=Le(t,e).located,o=Rn(t,i,n).located,r=[...i.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...o.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),s=[],a=0;for(let d of r)d.start>a&&s.push({type:"text",value:t.slice(a,d.start)}),s.push(d.segment),a=d.end;let l=t.slice(a);return l&&s.push({type:"text",value:l}),s}function Dn(t,e){let{located:n,missing:i}=Le(t,e);return{valid:n.map(o=>o.param),invalid:i}}function De(t,e,n){let i=Le(t,e).located,{located:o,missing:r}=Rn(t,i,n);return{valid:o.map(s=>s.param),invalid:r}}function po(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var mo=100,fo=300,go=2,Me=class{constructor(e,n,i,o,r,s,a,l,d={}){this.store=e;this.getApiConfig=n;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,n=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==n)&&(e=i.text,n=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,n){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?In(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=crypto.randomUUID(),d=await vn(e,n,{sessionId:this.getSessionId(),requestId:l,source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(d.data.input??[]).filter(E=>E.source==="identified").map(E=>({id:crypto.randomUUID(),type:E.type,text:E.text})),u=Pn(d.data.suggestions??[],this.getOptionOverrides()),m=d.data.input??[],f=m[m.length-1],g=this.store.get().text,S,x;if(f?.state==="in_progress"){x=!0;let E=g.toLowerCase().lastIndexOf(f.text.toLowerCase());S=E!==-1?E:r}else x=!1,S=r;let p=u.filter(E=>E.type!=="placeholder")[0],b=null;if(p&&!w(Y(p))){let E=Q(g,S,x),P=oe(p.options,E);P&&(b={id:crypto.randomUUID(),placeholder:"",type:p.type,text:P.text,value:P.value,kind:P.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:P.metadata,icon:P.icon,icon_svg:P.icon_svg,image_url:P.image_url},u=u.filter(A=>A!==p),this.callbacks.onAutoMatch?.({active:p,matched:P,rawQuery:e}))}let y=d.data.custom_fields??null,v=this.callbacks.productsForResponse?.(y);this.store.set(E=>{let P=b?[...E.completedParams,b]:E.completedParams,A=De(E.text,P,c).valid,T=new Set(s.skippedParams.map(D=>D.id)),I=new Set(E.skippedParams.filter(D=>!T.has(D.id)).map(D=>D.type));return{suggestions:I.size>0?u.filter(D=>D.type==="placeholder"||!I.has(D.type)):u,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:S,filterInProgress:x,identifiedParams:A,customFields:y,...v!==void 0?{products:v}:{},...b?{completedParams:P}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:d.meta?.funnel_telemetry===!0})}catch(s){let a=po(s);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}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(go)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},mo),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),fo)}attemptFetch(e,n=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let r=i.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=H(i.text,i.filterBase,r),a=Q(i.text,s,i.filterInProgress),d=i.suggestions.filter(y=>y.type!=="placeholder")[0],c=w(i.activeFormatType),m=(d&&!c?X(d.options,a):[]).filter(y=>y.is_tappable),f=d&&!c?oe(d.options,a)!==null:!1,g=a.trim().length>0;if(m.length>0&&!f&&g||Re(i.text,i.completedParams.length,r))return!1;let{rawQuery:S,completedParams:x}=R(i.text,i.completedParams),h=S.length<i.lastRawQuery.length,p=Math.abs(S.length-i.lastRawQuery.length),b=n&&S!==i.lastRawQuery;return h||p>=e||b?(this.doFetch(S,x),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function ho(t){return t.nodeType===Node.DOCUMENT_NODE?!0:t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function j(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&ho(e)?e:t.ownerDocument??t}function O(t){return t.ownerDocument??t}function bo(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Mn(t){let e=j(t);return!bo(e)||typeof e.getSelection=="function"?null:e}function kn(t){let e=Mn(t);if(!e)return null;let n=O(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function _n(t,e){let n=t,i;try{i=n.getComposedRanges({shadowRoots:[e]})}catch{i=n.getComposedRanges(e)}return i.length>0?i[0]:null}function gt(t){let n=j(t).getSelection?.();return n||(O(t).getSelection?.()??null)}function z(t){let e=gt(t);if(!e||e.rangeCount===0)return null;let n=kn(t);if(n){let i=_n(e,n);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function ke(t){let e=gt(t);if(!e||e.rangeCount===0)return null;let n=kn(t);if(!n)return e.getRangeAt(0);let i=_n(e,n);if(!i)return null;let o=O(t).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function ge(t,e,n){let i=gt(t);if(!i)return null;if(Mn(t))return i.collapse(e,n),i;let o=O(t).createRange();return o.setStart(e,n),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function _e(t,e){let n=t?j(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ne=2,yo="magicx-aia";function Nn(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function So(t){let e=O(t),n=e.defaultView;if(!n?.getComputedStyle)return null;let i=t;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=n.getComputedStyle(i);if(o&&Nn(s.overflowX)||r&&Nn(s.overflowY))return i}if(i.classList.contains(yo))return null;i=i.parentElement}return null}function ht(t){let e=ke(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=So(t);if(!n||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=n.getBoundingClientRect();if(n.scrollWidth>n.clientWidth){let r=o.left+n.clientLeft,s=r+n.clientWidth;i.right>s?n.scrollLeft+=i.right-s+Ne:i.left<r&&(n.scrollLeft-=r-i.left+Ne)}if(n.scrollHeight>n.clientHeight){let r=o.top+n.clientTop,s=r+n.clientHeight;i.bottom>s?n.scrollTop+=i.bottom-s+Ne:i.top<r&&(n.scrollTop-=r-i.top+Ne)}}var Bn='[contenteditable="false"]',xo="strong[data-param-id]",re;function vo(){if(re!==void 0)return re;let t=globalThis.Intl.Segmenter;if(!t)return re=null,null;try{re=new t(void 0,{granularity:"grapheme"})}catch{re=null}return re??null}function Fe(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(Bn))return!0;n=n.parentNode}return!1}function He(t){return O(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return Fe(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Be(t){let e=He(t),n="",i=e.nextNode();for(;i;)n+=i.data,i=e.nextNode();return n}function bt(t){let e=He(t),n=0,i=e.nextNode();for(;i;)n+=i.data.length,i=e.nextNode();return n}function _(t){let e=z(t);if(!e)return null;let n=e.node,i=e.offset;if(!t.contains(n))return null;if(n.nodeType===Node.ELEMENT_NODE){let o=n;if(Fe(o,t)&&o!==t)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=Wn(o.childNodes[s],t);return r+Fn(o,t)}return n.nodeType!==Node.TEXT_NODE||Fe(n,t)?null:Fn(n,t)+i}function Wn(t,e){if(t.nodeType===Node.TEXT_NODE)return Fe(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(Bn))return 0;let i=0;for(let o of Array.from(n.childNodes))i+=Wn(o,e);return i}function Fn(t,e){let n=He(e),i=0,o=n.nextNode();for(;o;){if(o===t||t.nodeType===Node.ELEMENT_NODE&&t.contains(o))return i;i+=o.data.length,o=n.nextNode()}return i}function L(t,e){let n=O(t),i=Math.max(0,Math.min(e,bt(t))),o=He(t),r=0,s=null,a=0,l=o.nextNode(),d=null;for(;l;){let u=l.data.length;if(i<r+u){s=l,a=i-r;break}if(i===r+u){let m=o.nextNode();m?(s=m,a=0):(s=l,a=u);break}r+=u,d=l,l=o.nextNode()}let c=n.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==t&&t.contains(u)?a===0?c.setStartBefore(u):a===s.data.length?c.setStartAfter(u):c.setStart(s,a):c.setStart(s,a)}else d?c.setStart(d,d.data.length):c.setStart(t,0);c.collapse(!0),ge(t,c.startContainer,c.startOffset)&&(Eo(t,c,i),ht(t))}function Hn(t,e){if(!t||!e.contains(t))return null;let i=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(xo)??null;return i&&e.contains(i)?i:null}function Eo(t,e,n){let i=Hn(z(t)?.node??null,t);if(i&&i!==Hn(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${i.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function qn(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let i=_(t);return i!==null&&n===`${i}:${e}`}function Gn(t){return j(t).activeElement===t}function yt(t){let e=_(t);return e==null?!1:e>=bt(t)}function St(t,e){if(e<=0)return 0;let n=vo();if(!n)return e-1;let i=t.slice(0,e),o=0;for(let{index:r}of n.segment(i))r<e&&(o=r);return o}function J(t,e,n=[],i={}){let{rawQuery:o,completedParams:r}=R(t,e);return{query:t.trim(),raw_query:o,completed_params:fe(r,n),identified_params:me(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function xt(t,e){return t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?t.selectionStart!=null&&t.selectionStart===t.value.length:t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?yt(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function vt(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?_(t):null}var We=class{constructor(e,n){this.store=e;this.ctx=n}handleKeyDown(e){let n=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=o(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=xt(e.target,n),u=!!n.editingParam;if(!c&&!u&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(d)break;e.preventDefault();let g=w(n.activeFormatType)?this.dateEntryIndex(n,!1):l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:g});break}if(l.length===0)return;this.store.set({activeDropdownIndex:g});break}if(e.preventDefault(),l.length===0)return;if(w(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let g=Math.floor((n.filteredOptions.length-1)/s);if(Math.floor(n.activeDropdownIndex/s)===g){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(n.activeDropdownIndex),f=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[f]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!d)break;let m=xt(e.target,n),f=!!n.editingParam;if(!m&&!f)break;e.preventDefault();let g=w(n.activeFormatType)?this.dateEntryIndex(n,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:g});break}if(l.length===0)return;this.store.set({activeDropdownIndex:g});break}if(l.length===0)break;if(e.preventDefault(),w(n.activeFormatType)){this.stepDateWeek(n,-7);break}if(n.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=l.indexOf(n.activeDropdownIndex),u=c>0?c-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),w(n.activeFormatType)){this.stepDateDay(n,1);break}if(n.activeDropdownIndex%s<s-1){let m=n.activeDropdownIndex+1;m<n.filteredOptions.length&&n.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=n.editingTail;this.ctx.exitEditMode?.(),L(u,m);break}xt(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),w(n.activeFormatType)){this.stepDateDay(n,-1);break}if(n.activeDropdownIndex%s>0){let c=n.activeDropdownIndex-1;c>=0&&n.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let c=vt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingAnchor;this.ctx.exitEditMode?.(),L(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=vt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let c=vt(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable?this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,i,r):a&&a(J(n.text,n.completedParams,n.skippedParams,{identifiedParams:n.identifiedParams,isReady:n.isReady,customFields:n.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=n.filteredOptions.map((f,g)=>f.is_tappable?g:-1).filter(f=>f!==-1);if(c.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let u=c.indexOf(n.activeDropdownIndex),m;if(u<0)m=e.shiftKey?c.length-1:0;else{let f=e.shiftKey?-1:1;m=(u+f+c.length)%c.length}this.store.set({activeDropdownIndex:c[m]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingTail;this.ctx.exitEditMode?.(),L(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let n=this.store.get();if(n.filteredOptions.length===0)return null;let o=Math.floor((n.filteredOptions.length-1)/e)*e;for(let r=o;r<n.filteredOptions.length;r++)if(n.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,n){let i=k(new Date),o=e.filteredOptions.findIndex(s=>N(s)===i);if(o>=0)return o;let r=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(n?r[r.length-1]:r[0])??0}stepDateDay(e,n){for(let i=e.activeDropdownIndex+n;i>=0&&i<e.filteredOptions.length;i+=n)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,n){let i=e.activeDropdownIndex+n;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.flat()}getEffectiveColumns(e){let n=_e(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let o=_e(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let r=getComputedStyle(o).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(o===n)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,n,i,o){let r=_e(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(n[e])}};var qe=class{constructor(e,n,i={}){this.store=e;this.getOverrides=n;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,n){return this.hasOverride(e)&&!this.missCovers(e,n)}tick(e,n){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let r=Math.abs(i.query.length-o.query.length),s=i.query.length<o.query.length;if(n>1&&!s&&r<n)return"owns"}return this.ask(i),"asked"}sync(e){let n=this.resolveTarget(e);if(!n){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===n.key||this.ask(n)}resolveTarget(e){if(w(e.activeFormatType)||e.editingIdentified)return null;let n=e.editingParam;if(n&&e.editingAnchor!=null)return this.hasOverride(n.suggestionType)?{mode:"edit",key:n.id,type:n.suggestionType,suggestion:{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,n){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===n}ask(e){this.cancel();let n=this.getOverrides()?.[e.type],i=++this.version;if(!n||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=n(e.query,o.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(r)){this.commit(e,r,i);return}this.setSearch(e,"loading"),this.await(e,r,o.signal,i)}async await(e,n,i,o){let r;try{let s=await n;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||wo(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,n,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;n.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let r={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:n}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:n};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:r}))}n.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,n){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===n||this.store.set({optionSearch:{type:e.type,query:e.query,status:n}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function wo(t){return t instanceof Error&&t.name==="AbortError"}var Ge=class{constructor(e,n={}){this.store=e;this.callbacks=n}setActivePill(e){let n=this.store.get(),i=n.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((d,c)=>c!==e),s=n.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=R(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:o.text,otherPills:r.map(c=>c.text)})}let a=[...s,o,...r],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Vn="/products/",$n="https://relative.invalid";function Po(t){if(!t)return;let e;try{e=new URL(t,`${$n}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===$n?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function Un(t){let e=Po(t.item_url)??(t.handle?`${Vn}${encodeURIComponent(t.handle)}`:void 0);return{id:t.source_id,title:t.title,...e&&{url:e},imageUrl:t.image_url||null,...t.price&&{price:t.price},...t.vendor&&{vendor:t.vendor}}}function Et(t){return(t?.items.matched??[]).map(Un)}var $e=class{constructor(e,n,i=()=>!0){this.store=e;this.getConfig=n;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return Et(e)}async run(e,n,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>n.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,n);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],d=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(d)}catch(s){if(n.aborted||To(s)||(this.logOnce(s),r()))return;this.clear(i)}}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 To(t){return t instanceof Error&&t.name==="AbortError"}var Ve="(max-width: 768px)";var Co="var(--aia-option-row-height, 37px)",Io="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function Kn(t,e){return e?wt(1,Math.min(t,5)):wt(1,Math.min(t,4))}function wt(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Co} + ${Io})`}}function Tt(t,e){return!e&&t>=5}function Ct(t,e,n,i){if(!(!e&&t>=5&&Oo(n,i))){let s=Kn(t,e);return{...s,template:Pt(s.cols),scrollHintIndices:!e&&t>s.rows?[s.rows-1]:[]}}let r=6;return{...wt(2,3),template:Pt(2),scrollHintIndices:t>r?[r-2,r-1]:[]}}function Oo(t,e){return!t||t.length===0||e==null||e<=0||t.some(i=>i<=0)?!1:Math.ceil(Math.max(...t))*2<=e}function It(t){if(typeof document>"u")return null;let e=Array.from(t.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let n=document.createElement("div");n.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",n.appendChild(a)}t.appendChild(n);let i=Array.from(n.children).map(s=>s.offsetWidth);n.remove();let o=getComputedStyle(t),r=t.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function Pt(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function Ot(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Ve).matches}function At(t,e){return!t||t.length!==e.length?!1:t.every((n,i)=>n.text===e[i].text)}function Yn(t,e){let n=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=t.filteredOptionsLength>0||t.activePillHasNoOptions||t.hasProducts;if(t.inEditMode){let a=i?t.isFocused:!0;return s&&a}if(n==="auto"){let a=i?t.isFocused:!0,l=t.text.replace(/\s+$/,"").length,d=t.caretOffset==null||t.caretOffset>=l;return(s||t.isLoading)&&a&&d}return n==="manual"?(s||t.isLoading)&&t.pillTapped:!1}function he(t){if(t.editingIdentified){let{type:n,anchor:i}=t.editingIdentified;return`identified:${n}@${i}`}return t.editingParam!=null&&t.editingAnchor!=null?`edit:${t.editingParam?.id}`:`pill:${t.actionableSuggestions[0]?.type??""}`}function Qn(t){if(!t)return st();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function Ao(t){let e=Ee(t);return e?dn(e):st()}function Xn(t,e){let n=Ln(t.text,t.completedParams,t.identifiedParams),i=t.suggestions.filter(C=>C.type!=="placeholder"),o=i[0],r=t.suggestions.filter(C=>C.type==="placeholder").map(C=>C.text).join(" "),s=H(t.text,Math.min(t.filterBase,t.text.length),r),l=s===0&&Re(t.text,t.completedParams.length,r)?"":Q(t.text,s,t.filterInProgress),d=o?.options??[],c=t.editingParam!=null&&t.editingAnchor!=null,u,m,f,g;if(c&&t.editingParam&&t.editingAnchor!=null){let C=t.editingParam.id,ee=t.completedParams.some(Qi=>Qi.id===C),de=t.caretOffset??t.editingAnchor,tn=ee?"":t.text.slice(t.editingAnchor,de);m=tn.trim(),f=t.editingParam.options,g=t.editingParam.suggestionType,u=X(t.editingParam.options,tn)}else m=l.trim(),f=d,g=o?.type,u=X(d,l);let S=t.optionSearch,x=S!=null&&g!=null&&S.type===g;x&&S.status==="done"&&S.query===m&&(u=f);let h=x&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(C=>C.is_tappable));let b=t.editingIdentified,y=c?t.editingParam&&{type:t.editingParam.suggestionType,options:t.editingParam.options}:o,v=b?b.format:Y(y),E=c&&w(v)?ue(t.editingParam):null;E&&(v="date-range");let P=null,A=null;if(w(v)){let C=he({...t,actionableSuggestions:i}),ee=t.dateViewMonth;P=ee&&ee.key===C?{year:ee.year,month:ee.month}:b?Qn(b.iso):E?Qn(E.start):Ao(t.editingParam?.text),u=lt(P);let de=t.pendingRangeStart;v==="date-range"&&de&&de.key===C&&(A=de.iso)}let T=C=>p?C.is_tappable:!0,I;if(c){let C=t.editingParam?.options??[];I=t.editingParam!=null&&C.filter(T).length===0}else I=o!=null&&d.filter(T).length===0;let V=Yn({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:t.isFocused,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||h,pillTapped:t.pillTapped,activePillHasNoOptions:I,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),D=V&&t.activeDropdownIndex>=0&&!!u[t.activeDropdownIndex]?.is_tappable,M=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,Z=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||h||M,en=Z&&t.skeletonOptions!==null,Ki=en&&t.skeletonOptions?t.skeletonOptions:u,Yi=en?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:i,filteredOptions:u,dropdownLoading:Z,dropdownOptions:Ki,dropdownSuggestion:Yi,skeletonExiting:M,activeFormatType:v,dateView:P,dateRangeStart:A,placeholderText:r,optionQuery:m,isSearchingOptions:h,isDropdownOpen:V,isActivePillSelected:D}}function Ue(t){return t.mode==="fresh"?Ro(t):Lo(t)}function Ro(t){let{text:e,completedParams:n,suggestions:i,filterBase:o,filterInProgress:r}=t,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),d=H(e,o,l),c=Q(e,d,r),u=oe(a.options,c);if(!u)return null;let m=u.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),g=f>=0?f:Math.max(0,e.length-u.text.length),S=g+u.text.length,x=e.slice(g,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:x,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...n,b],suggestions:i.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function Lo(t){let{text:e,completedParams:n,editingParam:i,editingAnchor:o,editingTail:r}=t;if(n.some(b=>b.id===i.id))return null;let s=e.slice(o,r),a=oe(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),d=s.toLowerCase().lastIndexOf(l),c=o+Math.max(0,d),u=c+a.text.length,m=e.slice(c,u),f=u<e.length&&e[u]===" "?u+1:u,g=e.length,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},x=n.length,h=0;for(let b=0;b<n.length;b++){let y=F(e,n[b].text,h);if(y!==-1){if(y>=f){x=b;break}h=y+n[b].text.length}}let p=[...n];return p.splice(x,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}function jn(t,e){let n=t.actionableSuggestions[0];if(!n)return null;let i=t.filterBase,o=t.text.slice(0,i),r=o.length===0&&t.text.length===0,s=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(r||s)&&t.placeholderText&&(o=`${t.placeholderText} `);let a=Math.min(An(t.text,t.completedParams),o.length),l=wn(o.slice(a),e.text);l>0&&(o=o.slice(0,o.length-l));let d=o.length>0&&o[o.length-1]!==" ",c=`${o}${d?" ":""}${e.text} `,u=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,m=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=m>=0?u.slice(m,m+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:n.type,text:f,value:e.value,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},S=t.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...t.completedParams,g],newParamId:g.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:t.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text)},consumedSuggestion:n,remainingActionable:S}}function Ke(t){let e=w(t.activeFormatType)||t.filteredOptions.length===0?null:t.filteredOptions,n=t.editingParam,i=n?{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options}:t.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?i:null,skeletonRequested:!1}}function Ye(t,e,n){let i=t.slice(0,e),o=t.slice(n),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:n-e+(r?1:0)}}var Qe=class{constructor(e){this.deps=e}start(e){let n=this.deps.store.get();if(n.editingParam?.id===e)return;let i=n.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of n.completedParams){let a=F(n.text,s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null||!n.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?Ye(n.text,o,r):{text:n.text.slice(0,o)+e+n.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let n=this.deps.store.get(),i={caretOffset:e};n.editingParam&&n.editingAnchor!=null&&e!=null&&(e<n.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):n.editingTail!=null&&(i.editingTail=Math.max(n.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let n=this.deps.store.get();if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null&&e!=null&&(e<n.editingAnchor||e>n.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:R(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(h=>h.text!==e.text).map(h=>h.text)});let s=n.text.slice(0,o),a=n.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${l} `:l,u=s+c+a,m=u.length,f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},g=n.completedParams.findIndex(h=>h.id===i.id),S=n.completedParams.filter(h=>h.id!==i.id),x=g>=0?Math.min(g,S.length):S.length;S.splice(x,0,f),this.deps.store.set({text:u,completedParams:S,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...Ke(n)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let n=Ue({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});n&&(this.deps.store.set(n.patch),this.deps.scheduleSetCursor(n.caretPos))}};var Do=33,Mo=70,ko=120,_o=50,se="data-aia-placeholder-leaving",ae=new WeakMap;function Xe(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function No(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Jn(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function Zn(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(Jn(t,e,e.shown+1),e.shown>=e.target.length))return;let n=e.target[e.shown-1],i=n===" "||n==="-"?70:0;e.timer=setTimeout(()=>Zn(t,e),33+i)}function zn(t,e){Jn(t,e,0),e.timer=setTimeout(()=>Zn(t,e),33)}function ei(t,e){let n=ae.get(t);if(e===""){n&&(Xe(n),ae.delete(t)),t.removeAttribute(se),delete t.dataset.placeholder;return}if(n?.target===e)return;if(No(t)){n&&Xe(n),t.removeAttribute(se),ae.set(t,{target:e,shown:e.length,timer:null}),t.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=n&&n.shown>0?n:null;if(n&&Xe(n),ae.set(t,i),o){t.setAttribute(se,""),i.timer=setTimeout(()=>{i.timer=null,t.removeAttribute(se),t.isConnected&&zn(t,i)},170);return}t.removeAttribute(se),zn(t,i)}function ti(t){let e=ae.get(t);e&&(Xe(e),ae.delete(t))}var ni="https://ai-autocomplete.com";function Rt(t=ni){try{if(typeof window>"u"||!window.location)return t;let e=window.location.hostname;if(!e)return t;let n=new URL(t);return n.searchParams.set("utm_source",e),n.toString()}catch{return t}}function Lt(t,e){return t?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}function Dt(t){let e=s=>{s.ctrlKey||ii(s.target,t,s.deltaX,s.deltaY)||s.preventDefault()},n=0,i=0,o=s=>{let a=s.touches[0];a&&(n=a.clientX,i=a.clientY)},r=s=>{if(s.touches.length!==1)return;let a=s.touches[0],l=n-a.clientX,d=i-a.clientY;n=a.clientX,i=a.clientY,s.cancelable&&!ii(s.target,t,l,d)&&s.preventDefault()};return t.addEventListener("wheel",e,{passive:!1}),t.addEventListener("touchstart",o,{passive:!0}),t.addEventListener("touchmove",r,{passive:!1}),()=>{t.removeEventListener("wheel",e),t.removeEventListener("touchstart",o),t.removeEventListener("touchmove",r)}}function ii(t,e,n,i){let o=t instanceof Element?t:null;for(;o;){if(i!==0&&Fo(o,i)||n!==0&&Ho(o,n))return!0;if(o===e)break;o=o.parentElement}return!1}var oi=/^(auto|scroll|overlay)$/;function Fo(t,e){return t.scrollHeight<=t.clientHeight||!oi.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function Ho(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!oi.test(n.overflowX))return!1;let i=Math.abs(t.scrollLeft),o=t.scrollWidth-t.clientWidth;return(n.direction==="rtl"?e<0:e>0)?i<o-1:i>0}var ri=new WeakMap,si=new WeakSet;function B(t,e,n){if(ri.set(t,n),si.has(t))return;si.add(t);let i=()=>ri.get(t),o=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&t.contains(s)?s:null};e.onClick&&t.addEventListener("click",r=>{let s=o(r.target);s&&e.onClick?.(s,i(),r)}),e.onEnter&&t.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,i())},!0),e.onLeave&&t.addEventListener("mouseleave",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onLeave?.(s,i())},!0),e.preventMousedown&&t.addEventListener("mousedown",r=>r.preventDefault())}function W(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function q(t){t.offsetWidth}var Bo={selectedIso:null,selectedRange:null,rangeStart:null};function be(t){if(!w(t.activeFormatType))return Bo;let e=t.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?ce(i,o):null,rangeStart:t.dateRangeStart}}let n=ue(t.editingParam);return{selectedIso:n?null:dt(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function Mt(t){return t.pendingStart?ce(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function kt(t,e){if(t==null)return{selected:!1,inRange:!1};let{selectedIso:n,range:i}=e,o=t===n||i!=null&&(t===i.start||t===i.end),r=i!=null&&t>i.start&&t<i.end;return{selected:o,inRange:r}}var ai="data-aia-key";function G(t,e,n){let i=new Map;for(let s of Array.from(t.children)){let a=s.getAttribute(ai);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=n.keyOf(a,s);o.add(l);let d=i.get(l);d||(d=n.create(a,s),d.setAttribute(ai,l)),n.update?.(d,a,s),t.children[s]!==d&&t.insertBefore(d,t.children[s]??null),r.push(d)}for(let[s,a]of i)o.has(s)||a.remove();return r}function li(t,e){if(!e.interactive)return null;let n=e.options[W(t)];return n?.is_tappable?n:null}var Wo={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(t,e)=>{if(t.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(t.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let n=li(t,e);n&&(t.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&li(t,e)&&e.callbacks.onHighlight(W(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,W(t))}};function ci(t,e,n,i,o,r,s,a=!0){let l=t.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){l?.remove();return}if(!l){l=$o(),t.appendChild(l),q(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}B(l,Wo,{options:e,callbacks:s,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=rt(o));let c=l.querySelector(".magicx-aia-datepicker-grid");c&&qo(c,e,n,i,r)}function qo(t,e,n,i,o){let r=k(new Date),s=Mt({pendingStart:o.rangeStart,highlightedIso:N(e[n]),selected:o.selectedRange});G(t,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>Go(a),update:(a,l,d)=>{let c=N(l),u=kt(c,{selectedIso:o.selectedIso,range:s}),m=d===n&&l.is_tappable;a.id=`${i}-option-${d}`,a.dataset.aiaIndex=String(d),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function Go(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=ct(t);if(n==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",t.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(n),e.appendChild(i),e}function $o(){let t=document.createElement("div");t.className="magicx-aia-datepicker",t.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let n=document.createElement("span");n.className="magicx-aia-datepicker-month",n.setAttribute("data-aia-date-month",""),n.setAttribute("aria-live","polite"),e.append(di("prev","Previous month","\u2039"),n,di("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of ve){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,i.appendChild(s)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),t.append(e,i,o),t}function di(t,e,n){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${t}`,""),i.setAttribute("aria-label",e),i.textContent=n,i.disabled=!0,i}var Vo={itemSelector:"[data-aia-pill]",onClick:(t,e)=>{if(e.loading||t.disabled)return;let n=Number.parseInt(t.dataset.aiaPillIndex??"-1",10);n>=0&&e.onSelectPill(n)},preventMousedown:!0},ui=[125,69];function pi(t,e){return e?1:t===0?.7:t===1?.4:.2}function je(t,e,n,i,o=!1,r=!1,s=!1){let a=t.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",t.appendChild(a)),B(a,Vo,{onSelectPill:i,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<ui.length;l++){let d=ui[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(pi(l,!1)),a.appendChild(c)}return}r?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();G(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=l.text,d.disabled=!0,d},update:(l,d,c)=>{let u=l,m=s&&c===n&&!r,f=["magicx-aia-pill"];o&&f.push("magicx-aia-pill--rounded"),r&&f.push("magicx-aia-pill--skeleton"),u.className=f.join(" "),u.style.width="",u.style.opacity=String(pi(c,m)),u.dataset.aiaPillIndex=String(c),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),q(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function _t(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Uo=32;function mi(t,e){if(e.ctrlKey)return null;let n=e.deltaY||0,i=e.deltaX||0;if(!n||Math.abs(i)>=Math.abs(n))return null;let o=t.scrollWidth-t.clientWidth;if(o<=1)return null;let r=t.scrollLeft,s=n;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=t.clientWidth),Math.max(0,Math.min(o,r+s))}function Nt(t){let e=n=>{let i=mi(t,n);i!==null&&(n.preventDefault(),t.scrollLeft=i)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var fi=Intl.Segmenter,gi=fi?new fi(void 0,{granularity:"grapheme"}):null;function Ft(t){let e=t.trim().normalize("NFC").toUpperCase();if(gi)for(let n of gi.segment(e))return n.segment;return Array.from(e)[0]??"?"}var Ht=new WeakMap,hi=new WeakMap,Ko="Products";function bi(t,e,n,i,o,r="row",s="image"){let a=t.querySelector(".magicx-aia-products");if(e.length===0){a?.remove();return}if(!a){a=document.createElement("section"),a.className="magicx-aia-products",a.setAttribute("data-aia-products",""),a.setAttribute("role","group"),a.setAttribute("aria-labelledby",`${n}-products-label`);let d=document.createElement("div");d.className="magicx-aia-products-label",d.id=`${n}-products-label`,d.setAttribute("data-aia-products-label",""),d.textContent=Ko;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),Nt(c),a.append(d,c),t.appendChild(a)}a.setAttribute("data-aia-products-layout",r);let l=a.querySelector(".magicx-aia-products-row");if(l){G(l,e,{keyOf:d=>Yo(d),create:d=>Qo(d,i,o,s),update:(d,c,u)=>{d.id=`${n}-product-${u}`,d.dataset.aiaIndex=String(u),hi.get(d)?.(s)}}),q(l);for(let d of l.querySelectorAll("[data-aia-product]")){let c=Ht.get(d);c&&(Ht.delete(d),c())}}}function Bt(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let i of n)i.tabIndex=e?0:-1}function Yo(t){return[t.id,t.title,t.url,t.imageUrl,t.price,t.vendor].map(e=>e??"").join("\0")}function Qo(t,e,n,i){let o=document.createElement("a");o.className="magicx-aia-product",o.setAttribute("data-aia-product",""),o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.tabIndex=0;let r=document.createElement("span");r.className="magicx-aia-product-media",r.setAttribute("aria-hidden","true");let s=t.imageUrl?.trim(),a=!!s,l=()=>{r.replaceChildren(),r.toggleAttribute("data-aia-product-placeholder",i==="image"),r.toggleAttribute("data-aia-product-initial",i==="initial"),i==="initial"&&(r.textContent=Ft(t.title))};if(hi.set(o,u=>{u!==i&&(i=u,a||l())}),s){let u=document.createElement("img");u.onerror=()=>{a=!1,l()},u.className="magicx-aia-product-image",u.src=s,u.alt="",u.loading="lazy",u.decoding="async",r.appendChild(u)}else l();o.appendChild(r);let d=document.createElement("span");if(d.className="magicx-aia-product-body",t.vendor){let u=document.createElement("span");u.className="magicx-aia-product-vendor",u.textContent=t.vendor,d.appendChild(u)}let c=document.createElement("span");if(c.className="magicx-aia-product-title",c.textContent=t.title,d.appendChild(c),t.price){let u=document.createElement("span");u.className="magicx-aia-product-price",u.textContent=t.price,d.appendChild(u)}return o.appendChild(d),Ht.set(o,()=>{t.url&&(o.href=t.url),o.addEventListener("click",u=>{u.metaKey||u.ctrlKey||u.shiftKey||u.altKey||u.button!==0||(u.preventDefault(),e(t))})}),o.addEventListener("keydown",u=>{u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),e(t))}),o.addEventListener("focus",()=>n(!0)),o.addEventListener("blur",u=>{u.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),o}var Xo=80,jo=150,zo=280,Jo=16,Wt="--aia-option-enter-delay";function qt(t,e,n,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,t)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,n)/o));return Math.max(0,s-1-r)*80}function Gt(t,e){let n=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,t)/n))-1)*80+280}function $(t){if(!t)return null;let e=t.trim();if(e==="")return null;let n;try{n=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.href}function ye(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var yi={one:"item",other:"items"};function Zo(t,e=yi){let n=ye(t);if(n===null)return null;let i=typeof e=="string"?e:t===1?e.one:e.other;return i===""?n:`${n} ${i}`}function er(t){return $(t.image_url)!==null}var Si="http://www.w3.org/2000/svg",tr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function nr(t,e){let n=t.toLowerCase();return n.startsWith("on")||n.includes("href")||n==="style"||n==="xml:base"||n==="id"||n==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var ir=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],or=/^[a-zA-Z0-9#.,%\s()-]+$/;function rr(t){let e=[];for(let n of ir){let i=t.getAttribute(n);i===null||!or.test(i)||/url\s*\(/i.test(i)||e.push(`${n}: ${i.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function xi(t){for(let e of Array.from(t.attributes))nr(e.name,e.value)&&t.removeAttribute(e.name);rr(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!tr.has(n.localName)||n.namespaceURI!==Si?n.remove():xi(n)}else e.remove()}function Se(t){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(t,"image/svg+xml"),n=e.documentElement;return!n||n.localName!=="svg"||n.namespaceURI!==Si||e.getElementsByTagName("parsererror").length>0?null:(xi(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function $t(t){return t.text}var vi=new WeakMap;function sr(t,e,n){let i=e.length,o=Ot(),r=vi.get(t),s=n&&r&&At(r.options,e)?r.plan:null,a=!s&&!n&&Tt(i,o)?It(t):null,l=s??Ct(i,o,a?.rowWidths??null,a?.gridWidth??null);return n||vi.set(t,{options:e,plan:l}),t.style.gridTemplateColumns=l.template,t.style.setProperty("--aia-grid-max-height",l.maxHeight),t.querySelectorAll("[data-aia-option]").forEach((d,c)=>{d.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(c))}),l.cols}function Ei(t,e){if(e.loading||!e.interactive)return null;let n=e.options[W(t)];return n?.is_tappable?n:null}var ar={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=Ei(t,e);n&&(t.classList.add("magicx-aia-option--pressed"),e.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(t,e)=>{Ei(t,e)&&e.onHighlight(W(t))},onLeave:(t,e)=>e.onHighlight(-1,W(t))};function wi(t,e,n,i,o,r,s,a="",l="below",d=!0,c=!0,u=!0,m=!0){let f=t.querySelector(".aia-grid");if(e.length===0){f?.remove();return}f||(f=document.createElement("div"),f.className="aia-grid magicx-aia-grid",f.setAttribute("data-scroll",""),f.style.setProperty("--aia-grid-min","250px"),f.style.setProperty("--aia-grid-max","1fr"),f.style.setProperty("--aia-grid-gap","0"),t.appendChild(f)),B(f,ar,{options:e,onSelect:i,onHighlight:o,loading:s,interactive:m});let g=f.dataset.aiaGroup!==a;f.dataset.aiaGroup=a,lr(f,e,n,r,s,{showIcons:d,showImages:c,showCounts:u});let S=sr(f,e,s);dr(f,e.length,S,s,l),g&&(f.scrollTop=0)}function lr(t,e,n,i,o,r){let s=o?"1":"0",a=t.dataset.aiaGroup??"",{showIcons:l,showImages:d,showCounts:c}=r,u=l?g=>g.icon??g.icon_svg??"":()=>"",m=d?g=>$(g.image_url)??"":()=>"",f=c?g=>ye(g.item_count)??"":()=>"";G(t,e,{keyOf:g=>`${g.text}\0${u(g)}\0${m(g)}\0${f(g)}\0${s}\0${a}`,create:(g,S)=>{let x=cr(g,o,r);return o||(x.dataset.aiaEntering=""),x},update:(g,S,x)=>{let h=x===n&&!o;g.id=`${i}-option-${x}`,g.dataset.aiaIndex=String(x),g.setAttribute("aria-selected",String(h)),g.classList.toggle("magicx-aia-option--highlighted",h)}})}function dr(t,e,n,i,o){for(let r of t.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Wt,`${qt(s,n,e,o)}ms`)}delete r.dataset.aiaEntering}}function cr(t,e,{showIcons:n,showImages:i,showCounts:o}){let r=document.createElement("div");r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),e&&r.setAttribute("data-aia-loading",""),r.tabIndex=e||!t.is_tappable?-1:0;let s=["magicx-aia-option"];t.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),r.className=s.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=i?$(t.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.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"),f.onerror=()=>{f.hidden=!0},f.src=l,m.appendChild(f),a.appendChild(m),r.dataset.aiaImage=""}let d=!l&&n&&t.icon_svg?Se(t.icon_svg):null;if(d){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=d,a.appendChild(m),t.icon&&(r.dataset.aiaIcon=t.icon)}let c=document.createElement("span");if(c.className="magicx-aia-option-text",c.textContent=$t(t),a.appendChild(c),t.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=t.tag,a.appendChild(m)}let u=o?ye(t.item_count):null;if(u!==null){let m=document.createElement("span");m.className="magicx-aia-option-count",m.textContent=u,a.appendChild(m),r.dataset.aiaItemCount=String(t.item_count)}return r.appendChild(a),r}var Pi="magicx-aia-scroll-arrow",Ti="data-aia-scroll-arrow",le="data-aia-visible",Ci=1e3,Ii=160,Oi="--aia-scroll-arrow-bottom",Ai="Scroll down for more options",ur="[data-aia-products-label]",pr=4,mr=8,fr=240;function gr(t,e,n,i){let o=t.scrollTop,r=n?.requestAnimationFrame,s=t.ownerDocument?.visibilityState==="hidden";if(!r||s||Vt(t)){t.scrollTop=o+e,i();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),d=()=>{let c=Math.min(1,(l()-a)/fr),u=1-(1-c)*(1-c);t.scrollTop=o+e*u,c<1?r.call(n,d):i()};r.call(n,d)}function hr(t=document){let e="http://www.w3.org/2000/svg",n=t.createElementNS(e,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("width","18"),n.setAttribute("height","18"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=t.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),n.appendChild(i),n}function Ri(t=document){let e=t.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Pi,e.setAttribute(Ti,""),e.setAttribute("aria-label",Ai),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(hr(t)),e}function br(t){let e=t.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Vt(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ut({dropdown:t,grid:e,button:n}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1;n.disabled=!0;let r=null,s=null,a=null,l=null,d=p=>{if(p){if(n.hasAttribute(le))return;if(n.setAttribute(le,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),Vt(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!o&&n.hasAttribute(le)&&(n.disabled=!1)},Ci)}else n.removeAttribute(le),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},c=p=>{let b=0,y=p;for(;y&&y!==t;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=t.querySelector(ur),b;if(p){let y=c(p)+p.offsetHeight/2;b=t.clientHeight-y-n.offsetHeight/2}else{let y=c(e),v=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;b=t.clientHeight-(y+e.offsetHeight)+(v>0?0:mr)}n.style.setProperty(Oi,`${Math.max(0,Math.round(b))}px`)},m=()=>{if(o||s!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,b=e.scrollHeight-e.clientHeight-e.scrollTop;d(!p&&b>pr)},f=()=>{if(o)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,d(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=Vt(e)?0:Gt(b,br(e));s=setTimeout(()=>{s=null,m()},y);return}m()},g=()=>{o||s!==null||(d(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},Ii))};e.addEventListener("scroll",g,{passive:!0});let S=p=>p.preventDefault(),x=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-p);gr(e,b,i,g)};n.addEventListener("mousedown",S),n.addEventListener("click",x);let h=null;return i&&typeof i.ResizeObserver=="function"&&(h=new i.ResizeObserver(()=>{u(),m()}),h.observe(e)),f(),{update:f,destroy(){o||(o=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,n.disabled=!0,e.removeEventListener("scroll",g),n.removeEventListener("mousedown",S),n.removeEventListener("click",x),h?.disconnect(),n.removeAttribute(le),n.setAttribute("aria-hidden","true"))}}}var yr=[159,119,164];function Je(t){let e=document.createElement("div");return e.id=t,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",n=>n.preventDefault()),Dt(e),e}var ze=new WeakMap;function Sr(t,e){let n=ze.get(t);if(n||(n={button:Ri(t.ownerDocument),grid:null,controller:null},t.appendChild(n.button),ze.set(t,n)),n.grid!==e&&(n.controller?.destroy(),n.controller=null,n.grid=e,e)){n.controller=Ut({dropdown:t,grid:e,button:n.button});return}n.controller?.update()}function Kt(t){let e=ze.get(t);e&&(e.controller?.destroy(),ze.delete(t))}function Ze(t,e){let{filteredOptions:n,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:m}=e,f=s.length>0,g=a&&f,S=n.length>0,x=e.products.length>0,h=o&&(S||g||r||x);if(h?t.classList.add("magicx-aia-dropdown--visible"):t.classList.remove("magicx-aia-dropdown--visible"),r?t.setAttribute("data-aia-loading",""):t.removeAttribute("data-aia-loading"),!h){Bt(t,!1);return}x?t.setAttribute("data-aia-has-products",""):t.removeAttribute("data-aia-has-products"),t.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let p=t.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),t.appendChild(p));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=g||r&&a||b,v=p.querySelector(".magicx-aia-pill-bar");if(y){v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar aia-cluster",v.setAttribute("data-nowrap",""),v.setAttribute("data-aia-pillbar",""),p.insertBefore(v,p.firstChild));let M=v.querySelector(".magicx-aia-pill-scroll");M||(M=document.createElement("span"),M.className="magicx-aia-pill-scroll",M.setAttribute("data-aia-pill-scroll",""),v.insertBefore(M,v.firstChild)),je(M,a?s:[],0,u,!0,r&&a,l),Er(v,b,r||e.skipDisabled,s[0],m)}else v&&v.remove();let E=e.suggestions[0],P=E?`${E.type} ${E.text}`:"",A=w(e.formatType),T=A&&!r;wi(p,A?[]:n,i,d,c,e.listboxId,r,P,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Sr(t,p.querySelector(".aia-grid")),ci(p,T?n:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let I=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||A)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let M of yr){let Z=document.createElement("span");Z.className="magicx-aia-skeleton-bar",Z.style.width=`${M}px`,I.appendChild(Z)}p.appendChild(I)}}else I&&I.remove();bi(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),Bt(t,!0);let V=p.querySelector(".magicx-aia-footer")??Pr(),D=i>=0&&!!n[i]?.is_tappable;wr(V,Lt(D,e.isInputEmpty)),V.isConnected||p.appendChild(V),xr(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function xr(t,e){let n=e.map(i=>t.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<n.length;i++)t.children[i]!==n[i]&&t.insertBefore(n[i],t.children[i]??null)}var vr={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function Er(t,e,n,i,o){B(t,vr,{onSkip:o,loading:n});let r=t.querySelector(".magicx-aia-skip");if(!e){r?.remove();return}r||(r=document.createElement("button"),r.type="button",r.tabIndex=-1,r.className="magicx-aia-skip",r.setAttribute("data-aia-skip",""),r.textContent="skip",r.disabled=!0,t.appendChild(r),q(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=n}function wr(t,{key:e,hint:n}){let i=t.querySelector(".magicx-aia-footer-key"),o=t.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==n&&(o.textContent=n))}function Pr(){let t=document.createElement("footer");t.className="magicx-aia-footer",t.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let n=document.createElement("div");n.className="aia-cluster magicx-aia-footer-hint-group",n.setAttribute("data-align","center"),n.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",n.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=Rt(),r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(n,r),t.append(e),t}function Li(t,e){let n=Je(e.listboxId);return t.appendChild(n),{dropdown:n}}function Yt(t,e,n){let i=be(e);Ze(t.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:U(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.dropdownSuggestion??e.actionableSuggestions[0]?[{...e.dropdownSuggestion??e.actionableSuggestions[0],options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:n.selectOption,onHighlight:(o,r)=>{r!==void 0&&n.store.get().activeDropdownIndex!==r||n.store.set({activeDropdownIndex:o})},onPillClick:n.setActivePill,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:o=>n.store.set({isFocused:o})})}var Tr=6,Cr=.3;function Di(t){return t<=0?"0px":`${(-Math.min(Cr,2*Tr/t)).toFixed(3)}px`}function Qt(t){let{input:e,segments:n,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=t,a=t.showChipIcons??!0,l=t.showChipImages??!0,d=n.length===0;e.dataset.aiaEmpty=d?"true":"false",ei(e,d?r:"");let c=n.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?$(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(c===u&&(i??"")===m&&(o??"")===f)return;if(c===u){e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";for(let p of e.querySelectorAll("strong[data-param-id]")){let b=p.dataset.paramId,y=p.dataset.seg==="completed"&&b===i;p.classList.toggle("magicx-aia-shimmer-revealed",y),p.classList.toggle("magicx-aia-shimmer-sweep",y),p.classList.toggle("magicx-aia-segment--editing",b===o)}return}let g=s?_(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let S=O(e),x=S.createDocumentFragment(),h=0;for(let p of n)if(h+=p.value.length,p.type==="completed"){let b=S.createElement("strong");b.dataset.seg="completed",b.dataset.paramId=p.param.id;let y=p.param.id===i,v=p.param.id===o,E=["magicx-aia-segment","magicx-aia-segment--completed"];y&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),v&&E.push("magicx-aia-segment--editing"),b.className=E.join(" "),b.style.letterSpacing=Di(p.value.length);let P=l?$(p.param.image_url):null;if(P){let T=S.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${P}")`),b.appendChild(T),b.dataset.aiaImage=""}let A=!P&&a&&p.param.icon_svg?Se(p.param.icon_svg):null;if(A){let T=S.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=A,b.appendChild(T),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),x.appendChild(b)}else if(p.type==="identified"){let b=S.createElement("strong");b.dataset.seg="identified",b.dataset.paramId=p.param.id;let y=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===o&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=Di(p.value.length),b.textContent=p.value,x.appendChild(b)}else x.appendChild(S.createTextNode(p.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(h),g!=null?L(e,Math.max(0,Math.min(g,h))):s&&Gn(e)&&L(e,h)}var Ir='<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 Mi(){let t=document.createElement("button");return t.type="button",t.className="magicx-aia-submit",t.setAttribute("aria-label","Submit"),t.setAttribute("data-aia-submit",""),t.innerHTML=Ir,t}function Or(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function ki(t,e){let n=e.firstElementChild;if(!n){e.removeAttribute("data-aia-pill-wrapped");return}let i=n.getBoundingClientRect(),o=t.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function _i(t,e){let{listboxId:n}=e,i=Je(n);t.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),t.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",Or()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",n),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=Mi(),o.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),d.setAttribute("data-aia-submit-slot",""),o.appendChild(d));let c=new AbortController,{signal:u}=c,m=!1,f=0,g=()=>{let h=Be(s),b=h.length>0&&h[0]!==h[0].toUpperCase()?h[0].toUpperCase()+h.slice(1):h;e.handleChange(b)},S=()=>{let h=z(s)?.node??null;if(!h||!s.contains(h))return null;let y=(h.nodeType===Node.ELEMENT_NODE?h:h.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&qn(s,y)?null:y};if(o.addEventListener("click",h=>{h.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(f=performance.now(),g(),e.handleCaretAfterInput(_(s)))},{signal:u}),O(s).addEventListener("selectionchange",()=>{let h=z(s);if(!h||!s.contains(h.node))return;let p=h.collapsed?S():null,b=e.store.get(),y=b.editingParam?.id??b.editingIdentified?.id??null;if(p&&p!==y){e.startEditingParam(p);return}performance.now()-f<50||e.handleCaretMove(_(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,g()},{signal:u}),s.addEventListener("beforeinput",h=>{let p=h,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){h.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(y)&&h.preventDefault()}},{signal:u}),s.addEventListener("paste",h=>{h.preventDefault();let p=(h.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=O(s),y=ke(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let v=b.createTextNode(p);y.insertNode(v),y.setStartAfter(v),ge(s,y.startContainer,y.startOffset),g()},{signal:u}),s.addEventListener("keydown",h=>e.handleKeyDown(h),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",h=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;h.stopPropagation(),e.onSubmit(J(p.text,p.completedParams,p.skippedParams,{identifiedParams:p.identifiedParams,isReady:p.isReady,customFields:p.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let h=z(s);(!h||!s.contains(h.node))&&ge(s,s,0)}if(typeof ResizeObserver<"u"){let h=new ResizeObserver(()=>ki(s,a));h.observe(s),c.signal.addEventListener("abort",()=>h.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:c}}function Xt(t,e,n){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=t,{pillPlacement:a,setActivePill:l,selectOption:d,store:c}=n;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${n.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let h=!!e.text||e.completedParams.length>0;s.disabled=!h}let m=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==m;if(Qt({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:n.showChipIcons??!0,showChipImages:n.showChipImages??!0}),a==="inline"){let h=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;h||e.actionableSuggestions.length>0?je(o,e.actionableSuggestions,0,l,!1,h,e.isActivePillSelected):_t(o)}else _t(o);ki(i,o),f?(i.focus(),L(i,e.caretOffset??e.text.length)):e.isFocused&&Be(i)!==e.text&&L(i,e.text.length);let g=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:U(e.editingIdentified.type),required:!0,options:[]}:null,S=e.dropdownSuggestion??g??e.actionableSuggestions[0],x=be(e);Ze(r,{suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:g?[g]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:x.selectedIso,selectedDateRange:x.selectedRange,dateRangeStart:x.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:d,onHighlight:(h,p)=>{p!==void 0&&c.get().activeDropdownIndex!==p||c.set({activeDropdownIndex:h})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:h=>c.set({isFocused:h})})}function jt(t){let e=t,n=new Set,i=[],o=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},i.push([e,a]),!o){o=!0;try{let l=0;for(let d=i.shift();d;d=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,u]=d;for(let m of n)m(c,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(n.add(r),()=>{n.delete(r)})}}function Ni(t,e){let n,i,o=r=>(r!==n&&(n=r,i=e(r)),i);return{get:()=>{let r=t.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?t.set(s=>{let a={...s,...o(s)};return r(a)}):t.set(r)},peek:r=>{let s={...t.get(),...r};return{...s,...e(s)}},subscribe:r=>t.subscribe((s,a)=>{let l={...a,...o(a)},d={...s,...o(s)};r(d,l)})}}var zt=new WeakSet,Fi=new WeakMap;function Bi(t){return t.nodeType===Node.DOCUMENT_NODE}function Ar(t){return Bi(t)?t:t.ownerDocument}function Rr(t){let e=Fi.get(t);if(e)return e;let n=t.defaultView?.CSSStyleSheet;if(typeof n!="function")return null;try{let i=new n;return typeof i.replaceSync!="function"?null:(i.replaceSync(qi),Fi.set(t,i),i)}catch{return null}}function Hi(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=qi,e.appendChild(n)}function Wi(t){if(typeof document>"u")return;let e=t??document;if(zt.has(e))return;let n=Ar(e);if(Bi(e)){let r=e.head??e.documentElement;if(!r)return;Hi(n,r),zt.add(e);return}let i=Rr(n),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):Hi(n,e),zt.add(e)}var qi=`.aia-stack {
1
+ function ot(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function K(t){let e=ot(t);return e.length>0?e.join(" "):t}var te=["January","February","March","April","May","June","July","August","September","October","November","December"],Ee=["S","M","T","W","T","F","S"],un=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],pn="aiaDate",mn="aiaDay",dn=t=>String(t).padStart(2,"0");function k(t){return`${t.getFullYear()}-${dn(t.getMonth()+1)}-${dn(t.getDate())}`}function rt(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function Zi(t){let e=rt(t).getTime()-rt(new Date).getTime();return Math.round(e/864e5)}function fn(t){let e=Zi(t);return e>=0&&e<7?un[t.getDay()]:ne(t)}function ne(t){return t.getFullYear()===new Date().getFullYear()?`${te[t.getMonth()]} ${t.getDate()}`:`${te[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function we(t){if(!t)return null;let e=un.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=rt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let n=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(t);if(!n)return null;let i=te.findIndex(a=>a.toLowerCase()===n[1].toLowerCase());if(i<0)return null;let o=Number(n[2]),r=n[3]?Number(n[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function st(t){return`${te[t.month]} ${t.year}`}function at(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function gn(t){return{year:t.getFullYear(),month:t.getMonth()}}function lt(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function cn(){return{text:"",is_tappable:!1,kind:null}}function dt(t){let e=new Date(t.year,t.month,1).getDay(),n=new Date(t.year,t.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(cn());for(let o=1;o<=n;o++){let r=new Date(t.year,t.month,o);i.push({text:fn(r),is_tappable:!0,kind:null,metadata:{[pn]:k(r),[mn]:o}})}for(;i.length%Ee.length!==0;)i.push(cn());return i}function ct(t){let e=we(t);return e?k(e):null}function N(t){let e=t?.metadata?.[pn];return typeof e=="string"?e:null}function ut(t){let e=t?.metadata?.[mn];return typeof e=="number"?e:null}function eo(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function hn(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:te.findIndex(n=>n.toLowerCase().startsWith(e))}function to(t,e,n){let i=new Date(n.getFullYear(),t,e);if(i.getMonth()!==t||i.getDate()!==e)return null;let o=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(i>=o)return i;let r=new Date(n.getFullYear()+1,t,e);return r.getMonth()===t&&r.getDate()===e?r:null}function bn(t,e,n){let i=new Date(t,e,n);return i.getMonth()===e&&i.getDate()===n?i:null}function Y(t,e={}){if(!t)return null;let n=e.today??new Date,i=eo(t.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=bn(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?k(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(r){let l=hn(r[1]);if(l>=0)return Pe(l,Number(r[2]),r[3],n)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=hn(s[2]);if(l>=0)return Pe(l,Number(s[1]),s[3],n)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),d=Number(a[2]);return l>12&&d<=12?Pe(d-1,l,a[3],n):d>12&&l<=12?Pe(l-1,d,a[3],n):null}return null}function Pe(t,e,n,i){if(n){if(n.length!==4)return null;let r=bn(Number(n),t,e);return r?k(r):null}let o=to(t,e,i);return o?k(o):null}function pt(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:Y(t.text,e)}var Sn=" - ",ft="aiaDateRangeStart",gt="aiaDateRangeEnd";function ue(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var mt=/^\d{4}-\d{2}-\d{2}$/;function yn(t){if(!mt.test(t))return null;let[e,n,i]=t.split("-").map(Number),o=new Date(e,n-1,i);return o.getMonth()===n-1&&o.getDate()===i?o:null}var no=/\s+(?:to|through|thru|until|til|till)\s+/g,io=/[-–—]/g;function oo(t){let e=[];for(let n of[no,io]){n.lastIndex=0;let i=n.exec(t);for(;i!==null;)e.push([t.slice(0,i.index),t.slice(i.index+i[0].length)]),i=n.exec(t)}return e}function ie(t,e={}){if(!t)return null;let n=new Set,i=null;for(let[o,r]of oo(t.trim())){let s=Y(o.trim(),e);if(!s)continue;let a=Y(r.trim(),e);!a||a<s||(n.add(`${s}|${a}`),i={start:s,end:a})}return n.size===1?i:null}function xn(t){let e=yn(t.start),n=yn(t.end);return!e||!n?"":t.start===t.end?ne(e):`${ne(e)}${Sn}${ne(n)}`}function vn(t,e){let n=ue(t,e);return{text:xn(n),is_tappable:!0,kind:null,metadata:{[ft]:n.start,[gt]:n.end}}}function pe(t,e={}){let n=t?.metadata?.[ft],i=t?.metadata?.[gt];return typeof n=="string"&&typeof i=="string"&&mt.test(n)&&mt.test(i)?ue(n,i):ie(t?.text,e)}function w(t){return t==="date"||t==="date-range"}var ro=new Set(["date","dates"]),so=new Set(["range","ranges","span","period","window"]),En=3;function ao(t){let e={single:0,range:0};if(!t)return e;for(let n of t)n.is_tappable&&(ie(n.text)!==null?e.range+=1:Y(n.text)!==null&&(e.single+=1));return e}function Q(t){if(!t)return"options";let e=t.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let n=ao(t.options);if(n.single+n.range>=En&&n.range>n.single)return"date-range";let i=ot(t.type);return i.some(o=>ro.has(o))?i.some(o=>so.has(o))?"date-range":"date":n.single>=En?"date":"options"}var Te=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 lo="https://api.ai-autocomplete.com",Ce=`${lo}/api/suggest`,wn=new WeakMap;function me(t){return t?.type==="accessToken"}function co(t){if(!(!t||me(t)))return t}function Ie(t){let e=wn.get(t.getAccessToken);return e||(e=new Te(t),wn.set(t.getAccessToken,e)),e}function Oe(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function Ae(t){let e=co(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function fe(t){return t.map(e=>({type:e.type,value:e.text}))}var Pn="skipped";function ge(t,e){if(e.length===0)return t;let n=new Set(t.map(o=>o.type)),i=e.filter(o=>!n.has(o.type)).map(o=>({placeholder:"",type:o.type,text:Pn,kind:null}));return i.length>0?[...t,...i]:t}var uo="0.35.0",Tn=!1;function po(t,e){return{placeholder:t.placeholder,type:t.type,...e&&{text:t.value??t.text},kind:t.kind}}function mo(t,e,n,i,o,r,s,a,l,d){let c=e.find(m=>m.type==="contact"&&m.metadata?.contact_account_count)?.metadata?.contact_account_count,u=typeof c=="number"?c:void 0;return{data:{raw_query:t,completed_params:ge(e.map(m=>po(m,n)),l??[]),...s&&s.length>0&&{identified_params:fe(s)},...a&&a.length>0&&{recently_suggested:a},...u!=null&&{contact_account_count:u},...d!==void 0&&{additional_context:d}},meta:{request_id:o,request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:uo,session_id:i,source:r}}}async function Cn(t,e,n,i,o){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:i,signal:o})}async function In(t,e,n){let i=n.apiConfig,o=!n.maskCompletedText,r=mo(t,e,o,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext),s=Oe(i),a=i?.endpoint??Ce,l=JSON.stringify(r);if(me(i)){let u=Ie(i),m=await u.getToken(),f=await Cn(a,s,m,l,n.signal);if(f.status===401){let h=await u.getToken(!0);f=await Cn(a,s,h,l,n.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let d=Ae(i);!d&&!Tn&&(Tn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(s.Authorization=d);let c=await fetch(a,{method:"POST",headers:s,body:l,signal:n.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}var Le=/[\p{L}\p{N}]/u,fo=/['\u2019-]/;function On(t,e,n){let i=t[e];if(i===void 0)return!1;if(Le.test(i))return!0;let o=t[e+n];return fo.test(i)&&o!==void 0&&Le.test(o)}function go(t,e,n){let i=e+n.length;return!(Le.test(n[0])&&On(t,e-1,-1)||Le.test(n[n.length-1])&&On(t,i,1))}function F(t,e,n=0,i=()=>!0){if(e.length===0)return t.indexOf(e,n);let o=-1,r=t.indexOf(e,n);for(;r!==-1;){if(i(r)){if(go(t,r,e))return r;o===-1&&(o=r)}r=t.indexOf(e,r+1)}return o}function R(t,e){let n=t,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=f=>F(n,a.text,f,h=>!r.some(S=>h<S.end&&h+a.text.length>S.start)),m=u(s);if(m===-1&&(m=u(0)),m!==-1){n=n.slice(0,m)+c+n.slice(m+a.text.length);let f=c.length-a.text.length;for(let h of r)h.start>=m+a.text.length&&(h.start+=f,h.end+=f);r.push({start:m,end:m+c.length}),s=m>=s?m+c.length:s+f}o.push({...a,placeholder:c})}return{rawQuery:n,completedParams:o}}function H(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function Re(t,e,n){return e===0&&t.length>0&&n.length>0&&n.toLowerCase().startsWith(t.toLowerCase())}function X(t,e,n){let i=t.slice(e);if(n||e===0||t[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function An(t,e){let n=t.trimEnd().replace(/\s+/g," ");if(n.length===0||e.length===0)return 0;let i=n.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=n.length-s.length;return t.length-a}}return 0}function j(t,e){if(!t)return[];let n=e.trimStart();if(!n)return t;let i=n.toLowerCase();return t.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function oe(t,e){if(!t)return null;let n=e.trim();if(!n)return null;let i=n.toLowerCase();return t.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function Ln(t,e){return e?t.map(n=>e[n.type]?{...n,options:[]}:n):t}function Rn(t,e){let n=0,i=e;for(let o of t)n+=o.value.length,o.type!=="text"&&(i=Math.max(i,n));return i}function Dn(t,e){let n=0;for(let i of t){let o=n+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-n,0)).trim().length>0)return!1;n=o}return!0}function Mn(t,e){let n=[],i=new Set;for(let o of[...t,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),n.push({type:o.type,text:o.text}));return n}function kn(t,e,n){if(t===e)return n;let i=Math.min(t.length,e.length),o=0;for(;o<i&&t[o]===e[o];)o++;if(o>=n)return n;let r=0;for(;r<i-o&&t[t.length-1-r]===e[e.length-1-r];)r++;return t.length-r<=n?n+(e.length-t.length):null}function De(t,e){let n=[],i=[],o=0;for(let r of e){let s=F(t,r.text,o);if(s===-1){i.push(r);continue}n.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:n,missing:i}}function _n(t,e){let{located:n}=De(t,e);return n.length>0?n[n.length-1].end:0}function Nn(t,e,n){let i=[],o=[],r=0;for(let s of n){let a=F(t,s.text,r,l=>!e.some(d=>l<d.end&&l+s.text.length>d.start));if(a===-1){o.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:i,missing:o}}function Fn(t,e,n=[]){let i=De(t,e).located,o=Nn(t,i,n).located,r=[...i.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...o.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),s=[],a=0;for(let d of r)d.start>a&&s.push({type:"text",value:t.slice(a,d.start)}),s.push(d.segment),a=d.end;let l=t.slice(a);return l&&s.push({type:"text",value:l}),s}function Hn(t,e){let{located:n,missing:i}=De(t,e);return{valid:n.map(o=>o.param),invalid:i}}function Me(t,e,n){let i=De(t,e).located,{located:o,missing:r}=Nn(t,i,n);return{valid:o.map(s=>s.param),invalid:r}}function ho(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var bo=100,yo=300,So=2,ke=class{constructor(e,n,i,o,r,s,a,l,d={}){this.store=e;this.getApiConfig=n;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,n=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==n)&&(e=i.text,n=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,n){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?Mn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=crypto.randomUUID(),d=await In(e,n,{sessionId:this.getSessionId(),requestId:l,source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(d.data.input??[]).filter(E=>E.source==="identified").map(E=>({id:crypto.randomUUID(),type:E.type,text:E.text})),u=Ln(d.data.suggestions??[],this.getOptionOverrides()),m=d.data.input??[],f=m[m.length-1],h=this.store.get().text,S,x;if(f?.state==="in_progress"){x=!0;let E=h.toLowerCase().lastIndexOf(f.text.toLowerCase());S=E!==-1?E:r}else x=!1,S=r;let p=u.filter(E=>E.type!=="placeholder")[0],b=null;if(p&&!w(Q(p))){let E=X(h,S,x),P=oe(p.options,E);P&&(b={id:crypto.randomUUID(),placeholder:"",type:p.type,text:P.text,value:P.value,kind:P.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:P.metadata,icon:P.icon,icon_svg:P.icon_svg,image_url:P.image_url},u=u.filter(L=>L!==p),this.callbacks.onAutoMatch?.({active:p,matched:P,rawQuery:e}))}let y=d.data.custom_fields??null,v=this.callbacks.productsForResponse?.(y);this.store.set(E=>{let P=b?[...E.completedParams,b]:E.completedParams,L=Me(E.text,P,c).valid,T=new Set(s.skippedParams.map(D=>D.id)),I=new Set(E.skippedParams.filter(D=>!T.has(D.id)).map(D=>D.type));return{suggestions:I.size>0?u.filter(D=>D.type==="placeholder"||!I.has(D.type)):u,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:S,filterInProgress:x,identifiedParams:L,customFields:y,...v!==void 0?{products:v}:{},...b?{completedParams:P}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:d.meta?.funnel_telemetry===!0})}catch(s){let a=ho(s);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}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(So)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},bo),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),yo)}attemptFetch(e,n=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let r=i.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=H(i.text,i.filterBase,r),a=X(i.text,s,i.filterInProgress),d=i.suggestions.filter(y=>y.type!=="placeholder")[0],c=w(i.activeFormatType),m=(d&&!c?j(d.options,a):[]).filter(y=>y.is_tappable),f=d&&!c?oe(d.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!f&&h||Re(i.text,i.completedParams.length,r))return!1;let{rawQuery:S,completedParams:x}=R(i.text,i.completedParams),g=S.length<i.lastRawQuery.length,p=Math.abs(S.length-i.lastRawQuery.length),b=n&&S!==i.lastRawQuery;return g||p>=e||b?(this.doFetch(S,x),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function xo(t){return t.nodeType===Node.DOCUMENT_NODE?!0:t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function z(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&xo(e)?e:t.ownerDocument??t}function O(t){return t.ownerDocument??t}function vo(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Bn(t){let e=z(t);return!vo(e)||typeof e.getSelection=="function"?null:e}function Wn(t){let e=Bn(t);if(!e)return null;let n=O(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function qn(t,e){let n=t,i;try{i=n.getComposedRanges({shadowRoots:[e]})}catch{i=n.getComposedRanges(e)}return i.length>0?i[0]:null}function ht(t){let n=z(t).getSelection?.();return n||(O(t).getSelection?.()??null)}function B(t){let e=ht(t);if(!e||e.rangeCount===0)return null;let n=Wn(t);if(n){let i=qn(e,n);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function _e(t){let e=ht(t);if(!e||e.rangeCount===0)return null;let n=Wn(t);if(!n)return e.getRangeAt(0);let i=qn(e,n);if(!i)return null;let o=O(t).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function he(t,e,n){let i=ht(t);if(!i)return null;if(Bn(t))return i.collapse(e,n),i;let o=O(t).createRange();return o.setStart(e,n),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ne(t,e){let n=t?z(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Fe=2,Eo="magicx-aia";function $n(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function wo(t){let e=O(t),n=e.defaultView;if(!n?.getComputedStyle)return null;let i=t;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=n.getComputedStyle(i);if(o&&$n(s.overflowX)||r&&$n(s.overflowY))return i}if(i.classList.contains(Eo))return null;i=i.parentElement}return null}function bt(t){let e=_e(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=wo(t);if(!n||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=n.getBoundingClientRect();if(n.scrollWidth>n.clientWidth){let r=o.left+n.clientLeft,s=r+n.clientWidth;i.right>s?n.scrollLeft+=i.right-s+Fe:i.left<r&&(n.scrollLeft-=r-i.left+Fe)}if(n.scrollHeight>n.clientHeight){let r=o.top+n.clientTop,s=r+n.clientHeight;i.bottom>s?n.scrollTop+=i.bottom-s+Fe:i.top<r&&(n.scrollTop-=r-i.top+Fe)}}var Un='[contenteditable="false"]',St="strong[data-param-id]",re;function Po(){if(re!==void 0)return re;let t=globalThis.Intl.Segmenter;if(!t)return re=null,null;try{re=new t(void 0,{granularity:"grapheme"})}catch{re=null}return re??null}function He(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(Un))return!0;n=n.parentNode}return!1}function Be(t){return O(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return He(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function We(t){let e=Be(t),n="",i=e.nextNode();for(;i;)n+=i.data,i=e.nextNode();return n}function xt(t){let e=Be(t),n=0,i=e.nextNode();for(;i;)n+=i.data.length,i=e.nextNode();return n}function _(t){let e=B(t);if(!e)return null;let n=e.node,i=e.offset;if(!t.contains(n))return null;if(n.nodeType===Node.ELEMENT_NODE){let o=n;if(He(o,t)&&o!==t)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=vt(o.childNodes[s],t);return r+yt(o,t)}return n.nodeType!==Node.TEXT_NODE||He(n,t)?null:yt(n,t)+i}function vt(t,e){if(t.nodeType===Node.TEXT_NODE)return He(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(Un))return 0;let i=0;for(let o of Array.from(n.childNodes))i+=vt(o,e);return i}function yt(t,e){let n=Be(e),i=0,o=n.nextNode();for(;o;){if(o===t||t.nodeType===Node.ELEMENT_NODE&&t.contains(o))return i;i+=o.data.length,o=n.nextNode()}return i}function A(t,e){let n=O(t),i=Math.max(0,Math.min(e,xt(t))),o=Be(t),r=0,s=null,a=0,l=o.nextNode(),d=null;for(;l;){let u=l.data.length;if(i<r+u){s=l,a=i-r;break}if(i===r+u){let m=o.nextNode();m?(s=m,a=0):(s=l,a=u);break}r+=u,d=l,l=o.nextNode()}let c=n.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==t&&t.contains(u)?a===0?c.setStartBefore(u):a===s.data.length?c.setStartAfter(u):c.setStart(s,a):c.setStart(s,a)}else d?c.setStart(d,d.data.length):c.setStart(t,0);c.collapse(!0),he(t,c.startContainer,c.startOffset)&&(To(t,c,i),bt(t))}function Gn(t,e){if(!t||!e.contains(t))return null;let i=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(St)??null;return i&&e.contains(i)?i:null}function To(t,e,n){let i=Gn(B(t)?.node??null,t);if(i&&i!==Gn(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${i.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function Vn(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let i=_(t);return i!==null&&n===`${i}:${e}`}function Kn(t){return z(t).activeElement===t}function Et(t,e){if(!e||e.nodeType===void 0)return null;let n=e,o=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(St);if(!o||!t.contains(o))return null;let r=B(t);return r&&!r.collapsed?null:o.dataset.paramId??null}function wt(t,e){let n=null;for(let s of t.querySelectorAll(St))if(s.dataset.paramId===e){n=s;break}if(!n)return;let i=yt(n,t),o=i+vt(n,t),r=_(t);r!=null&&r>=i&&r<=o||A(t,i)}function Pt(t){let e=_(t);return e==null?!1:e>=xt(t)}function Tt(t,e){if(e<=0)return 0;let n=Po();if(!n)return e-1;let i=t.slice(0,e),o=0;for(let{index:r}of n.segment(i))r<e&&(o=r);return o}function J(t,e,n=[],i={}){let{rawQuery:o,completedParams:r}=R(t,e);return{query:t.trim(),raw_query:o,completed_params:ge(r,n),identified_params:fe(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Ct(t,e){return t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?t.selectionStart!=null&&t.selectionStart===t.value.length:t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?Pt(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function It(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?_(t):null}var qe=class{constructor(e,n){this.store=e;this.ctx=n}handleKeyDown(e){let n=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=o(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=Ct(e.target,n),u=!!n.editingParam;if(!c&&!u&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(d)break;e.preventDefault();let h=w(n.activeFormatType)?this.dateEntryIndex(n,!1):l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(w(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let h=Math.floor((n.filteredOptions.length-1)/s);if(Math.floor(n.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(n.activeDropdownIndex),f=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[f]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!d)break;let m=Ct(e.target,n),f=!!n.editingParam;if(!m&&!f)break;e.preventDefault();let h=w(n.activeFormatType)?this.dateEntryIndex(n,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),w(n.activeFormatType)){this.stepDateWeek(n,-7);break}if(n.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=l.indexOf(n.activeDropdownIndex),u=c>0?c-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),w(n.activeFormatType)){this.stepDateDay(n,1);break}if(n.activeDropdownIndex%s<s-1){let m=n.activeDropdownIndex+1;m<n.filteredOptions.length&&n.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=n.editingTail;this.ctx.exitEditMode?.(),A(u,m);break}Ct(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),w(n.activeFormatType)){this.stepDateDay(n,-1);break}if(n.activeDropdownIndex%s>0){let c=n.activeDropdownIndex-1;c>=0&&n.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let c=It(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingAnchor;this.ctx.exitEditMode?.(),A(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=It(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let c=It(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable?this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,i,r):a&&a(J(n.text,n.completedParams,n.skippedParams,{identifiedParams:n.identifiedParams,isReady:n.isReady,customFields:n.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=n.filteredOptions.map((f,h)=>f.is_tappable?h:-1).filter(f=>f!==-1);if(c.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let u=c.indexOf(n.activeDropdownIndex),m;if(u<0)m=e.shiftKey?c.length-1:0;else{let f=e.shiftKey?-1:1;m=(u+f+c.length)%c.length}this.store.set({activeDropdownIndex:c[m]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingTail;this.ctx.exitEditMode?.(),A(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let n=this.store.get();if(n.filteredOptions.length===0)return null;let o=Math.floor((n.filteredOptions.length-1)/e)*e;for(let r=o;r<n.filteredOptions.length;r++)if(n.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,n){let i=k(new Date),o=e.filteredOptions.findIndex(s=>N(s)===i);if(o>=0)return o;let r=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(n?r[r.length-1]:r[0])??0}stepDateDay(e,n){for(let i=e.activeDropdownIndex+n;i>=0&&i<e.filteredOptions.length;i+=n)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,n){let i=e.activeDropdownIndex+n;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.flat()}getEffectiveColumns(e){let n=Ne(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let o=Ne(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let r=getComputedStyle(o).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(o===n)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,n,i,o){let r=Ne(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(n[e])}};var $e=class{constructor(e,n,i={}){this.store=e;this.getOverrides=n;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,n){return this.hasOverride(e)&&!this.missCovers(e,n)}tick(e,n){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let r=Math.abs(i.query.length-o.query.length),s=i.query.length<o.query.length;if(n>1&&!s&&r<n)return"owns"}return this.ask(i),"asked"}sync(e){let n=this.resolveTarget(e);if(!n){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===n.key||this.ask(n)}resolveTarget(e){if(w(e.activeFormatType)||e.editingIdentified)return null;let n=e.editingParam;if(n&&e.editingAnchor!=null)return this.hasOverride(n.suggestionType)?{mode:"edit",key:n.id,type:n.suggestionType,suggestion:{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,n){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===n}ask(e){this.cancel();let n=this.getOverrides()?.[e.type],i=++this.version;if(!n||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=n(e.query,o.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(r)){this.commit(e,r,i);return}this.setSearch(e,"loading"),this.await(e,r,o.signal,i)}async await(e,n,i,o){let r;try{let s=await n;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||Co(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,n,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;n.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let r={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:n}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:n};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:r}))}n.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,n){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===n||this.store.set({optionSearch:{type:e.type,query:e.query,status:n}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Co(t){return t instanceof Error&&t.name==="AbortError"}var Ge=class{constructor(e,n={}){this.store=e;this.callbacks=n}setActivePill(e){let n=this.store.get(),i=n.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((d,c)=>c!==e),s=n.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=R(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:o.text,otherPills:r.map(c=>c.text)})}let a=[...s,o,...r],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Qn="/products/",Yn="https://relative.invalid";function Io(t){if(!t)return;let e;try{e=new URL(t,`${Yn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===Yn?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function Xn(t){let e=Io(t.item_url)??Oo(t);return{id:t.source_id,title:t.title,...e&&{url:e},imageUrl:t.image_url||null,...t.price&&{price:t.price},...t.vendor&&{vendor:t.vendor},...typeof t.available=="boolean"&&{available:t.available}}}function Oo(t){if(!t.handle)return;let e=`${Qn}${encodeURIComponent(t.handle)}`;return t.variant_id?`${e}?variant=${encodeURIComponent(t.variant_id)}`:e}function Ot(t){return(t?.items.matched??[]).map(Xn)}var Ue=class{constructor(e,n,i=()=>!0){this.store=e;this.getConfig=n;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return Ot(e)}async run(e,n,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>n.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,n);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],d=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(d)}catch(s){if(n.aborted||Ao(s)||(this.logOnce(s),r()))return;this.clear(i)}}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 Ao(t){return t instanceof Error&&t.name==="AbortError"}var Ve="(max-width: 768px)";var Lo="var(--aia-option-row-height, 37px)",Ro="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function jn(t,e){return e?At(1,Math.min(t,5)):At(1,Math.min(t,4))}function At(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Lo} + ${Ro})`}}function Rt(t,e){return!e&&t>=5}function Dt(t,e,n,i){if(!(!e&&t>=5&&Do(n,i))){let s=jn(t,e);return{...s,template:Lt(s.cols),scrollHintIndices:!e&&t>s.rows?[s.rows-1]:[]}}let r=6;return{...At(2,3),template:Lt(2),scrollHintIndices:t>r?[r-2,r-1]:[]}}function Do(t,e){return!t||t.length===0||e==null||e<=0||t.some(i=>i<=0)?!1:Math.ceil(Math.max(...t))*2<=e}function Mt(t){if(typeof document>"u")return null;let e=Array.from(t.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let n=document.createElement("div");n.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",n.appendChild(a)}t.appendChild(n);let i=Array.from(n.children).map(s=>s.offsetWidth);n.remove();let o=getComputedStyle(t),r=t.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function Lt(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function kt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Ve).matches}function _t(t,e){return!t||t.length!==e.length?!1:t.every((n,i)=>n.text===e[i].text)}function zn(t,e){let n=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=t.filteredOptionsLength>0||t.activePillHasNoOptions||t.hasProducts;if(t.inEditMode){let a=i?t.isFocused:!0;return s&&a}if(n==="auto"){let a=i?t.isFocused:!0,l=t.text.replace(/\s+$/,"").length,d=t.caretOffset==null||t.caretOffset>=l;return(s||t.isLoading)&&a&&d}return n==="manual"?(s||t.isLoading)&&t.pillTapped:!1}function be(t){if(t.editingIdentified){let{type:n,anchor:i}=t.editingIdentified;return`identified:${n}@${i}`}return t.editingParam!=null&&t.editingAnchor!=null?`edit:${t.editingParam?.id}`:`pill:${t.actionableSuggestions[0]?.type??""}`}function Jn(t){if(!t)return at();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function Mo(t){let e=we(t);return e?gn(e):at()}function Zn(t,e){let n=Fn(t.text,t.completedParams,t.identifiedParams),i=t.suggestions.filter(C=>C.type!=="placeholder"),o=i[0],r=t.suggestions.filter(C=>C.type==="placeholder").map(C=>C.text).join(" "),s=H(t.text,Math.min(t.filterBase,t.text.length),r),l=s===0&&Re(t.text,t.completedParams.length,r)?"":X(t.text,s,t.filterInProgress),d=o?.options??[],c=t.editingParam!=null&&t.editingAnchor!=null,u,m,f,h;if(c&&t.editingParam&&t.editingAnchor!=null){let C=t.editingParam.id,ee=t.completedParams.some(Ji=>Ji.id===C),ce=t.caretOffset??t.editingAnchor,ln=ee?"":t.text.slice(t.editingAnchor,ce);m=ln.trim(),f=t.editingParam.options,h=t.editingParam.suggestionType,u=j(t.editingParam.options,ln)}else m=l.trim(),f=d,h=o?.type,u=j(d,l);let S=t.optionSearch,x=S!=null&&h!=null&&S.type===h;x&&S.status==="done"&&S.query===m&&(u=f);let g=x&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(C=>C.is_tappable));let b=t.editingIdentified,y=c?t.editingParam&&{type:t.editingParam.suggestionType,options:t.editingParam.options}:o,v=b?b.format:Q(y),E=c&&w(v)?pe(t.editingParam):null;E&&(v="date-range");let P=null,L=null;if(w(v)){let C=be({...t,actionableSuggestions:i}),ee=t.dateViewMonth;P=ee&&ee.key===C?{year:ee.year,month:ee.month}:b?Jn(b.iso):E?Jn(E.start):Mo(t.editingParam?.text),u=dt(P);let ce=t.pendingRangeStart;v==="date-range"&&ce&&ce.key===C&&(L=ce.iso)}let T=C=>p?C.is_tappable:!0,I;if(c){let C=t.editingParam?.options??[];I=t.editingParam!=null&&C.filter(T).length===0}else I=o!=null&&d.filter(T).length===0;let V=zn({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:t.isFocused,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||g,pillTapped:t.pillTapped,activePillHasNoOptions:I,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),D=V&&t.activeDropdownIndex>=0&&!!u[t.activeDropdownIndex]?.is_tappable,M=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,Z=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||g||M,an=Z&&t.skeletonOptions!==null,ji=an&&t.skeletonOptions?t.skeletonOptions:u,zi=an?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:i,filteredOptions:u,dropdownLoading:Z,dropdownOptions:ji,dropdownSuggestion:zi,skeletonExiting:M,activeFormatType:v,dateView:P,dateRangeStart:L,placeholderText:r,optionQuery:m,isSearchingOptions:g,isDropdownOpen:V,isActivePillSelected:D}}function Ke(t){return t.mode==="fresh"?ko(t):_o(t)}function ko(t){let{text:e,completedParams:n,suggestions:i,filterBase:o,filterInProgress:r}=t,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),d=H(e,o,l),c=X(e,d,r),u=oe(a.options,c);if(!u)return null;let m=u.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),h=f>=0?f:Math.max(0,e.length-u.text.length),S=h+u.text.length,x=e.slice(h,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:x,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...n,b],suggestions:i.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function _o(t){let{text:e,completedParams:n,editingParam:i,editingAnchor:o,editingTail:r}=t;if(n.some(b=>b.id===i.id))return null;let s=e.slice(o,r),a=oe(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),d=s.toLowerCase().lastIndexOf(l),c=o+Math.max(0,d),u=c+a.text.length,m=e.slice(c,u),f=u<e.length&&e[u]===" "?u+1:u,h=e.length,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},x=n.length,g=0;for(let b=0;b<n.length;b++){let y=F(e,n[b].text,g);if(y!==-1){if(y>=f){x=b;break}g=y+n[b].text.length}}let p=[...n];return p.splice(x,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}var No=6e4;function Fo(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function Ho(t){return(t??Ce).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Bo(t){return me(t)?`Bearer ${await Ie(t).getToken()}`:Ae(t)}async function ei(t){try{let e=Ho(t.apiConfig?.endpoint),n=Oe(t.apiConfig),i=await Bo(t.apiConfig);i&&(n.Authorization=i);let o=JSON.stringify({source:t.source,session_id:t.sessionId,...t.visitorId&&{visitor_id:t.visitorId},...t.requestId&&{request_id:t.requestId},type:t.type,at:new Date().toISOString(),query_data:t.queryData});await fetch(e,{method:"POST",headers:n,body:o,...t.keepalive&&Fo(o)<=No&&{keepalive:!0}})}catch{}}function se(t,e){let n=t.findIndex(i=>i.text===e);return n>=0?n+1:null}function ti(t,e){let n=t.actionableSuggestions[0];if(!n)return null;let i=t.filterBase,o=t.text.slice(0,i),r=o.length===0&&t.text.length===0,s=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(r||s)&&t.placeholderText&&(o=`${t.placeholderText} `);let a=Math.min(_n(t.text,t.completedParams),o.length),l=An(o.slice(a),e.text);l>0&&(o=o.slice(0,o.length-l));let d=o.length>0&&o[o.length-1]!==" ",c=`${o}${d?" ":""}${e.text} `,u=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,m=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=m>=0?u.slice(m,m+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:n.type,text:f,value:e.value,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},S=t.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...t.completedParams,h],newParamId:h.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:t.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text),key:n.type,position:se(n.options??[],e.text)},consumedSuggestion:n,remainingActionable:S}}function Ye(t){let e=w(t.activeFormatType)||t.filteredOptions.length===0?null:t.filteredOptions,n=t.editingParam,i=n?{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options}:t.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?i:null,skeletonRequested:!1}}function Qe(t,e,n){let i=t.slice(0,e),o=t.slice(n),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:n-e+(r?1:0)}}var Xe=class{constructor(e){this.deps=e}start(e){let n=this.deps.store.get();if(n.editingParam?.id===e)return;let i=n.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of n.completedParams){let a=F(n.text,s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null||!n.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?Qe(n.text,o,r):{text:n.text.slice(0,o)+e+n.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let n=this.deps.store.get(),i={caretOffset:e};n.editingParam&&n.editingAnchor!=null&&e!=null&&(e<n.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):n.editingTail!=null&&(i.editingTail=Math.max(n.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let n=this.deps.store.get();if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null&&e!=null&&(e<n.editingAnchor||e>n.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:R(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(g=>g.text!==e.text).map(g=>g.text),key:i.suggestionType,position:se(i.options,e.text)});let s=n.text.slice(0,o),a=n.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${l} `:l,u=s+c+a,m=u.length,f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=n.completedParams.findIndex(g=>g.id===i.id),S=n.completedParams.filter(g=>g.id!==i.id),x=h>=0?Math.min(h,S.length):S.length;S.splice(x,0,f),this.deps.store.set({text:u,completedParams:S,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...Ye(n)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let n=Ke({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});n&&(this.deps.store.set(n.patch),this.deps.scheduleSetCursor(n.caretPos))}};var Wo=33,qo=70,$o=120,Go=50,ae="data-aia-placeholder-leaving",le=new WeakMap;function je(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function Uo(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function ii(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function oi(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(ii(t,e,e.shown+1),e.shown>=e.target.length))return;let n=e.target[e.shown-1],i=n===" "||n==="-"?70:0;e.timer=setTimeout(()=>oi(t,e),33+i)}function ni(t,e){ii(t,e,0),e.timer=setTimeout(()=>oi(t,e),33)}function ri(t,e){let n=le.get(t);if(e===""){n&&(je(n),le.delete(t)),t.removeAttribute(ae),delete t.dataset.placeholder;return}if(n?.target===e)return;if(Uo(t)){n&&je(n),t.removeAttribute(ae),le.set(t,{target:e,shown:e.length,timer:null}),t.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=n&&n.shown>0?n:null;if(n&&je(n),le.set(t,i),o){t.setAttribute(ae,""),i.timer=setTimeout(()=>{i.timer=null,t.removeAttribute(ae),t.isConnected&&ni(t,i)},170);return}t.removeAttribute(ae),ni(t,i)}function si(t){let e=le.get(t);e&&(je(e),le.delete(t))}var ai="https://ai-autocomplete.com";function Nt(t=ai){try{if(typeof window>"u"||!window.location)return t;let e=window.location.hostname;if(!e)return t;let n=new URL(t);return n.searchParams.set("utm_source",e),n.toString()}catch{return t}}function Ft(t,e){return t?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}function Ht(t){let e=s=>{s.ctrlKey||li(s.target,t,s.deltaX,s.deltaY)||s.preventDefault()},n=0,i=0,o=s=>{let a=s.touches[0];a&&(n=a.clientX,i=a.clientY)},r=s=>{if(s.touches.length!==1)return;let a=s.touches[0],l=n-a.clientX,d=i-a.clientY;n=a.clientX,i=a.clientY,s.cancelable&&!li(s.target,t,l,d)&&s.preventDefault()};return t.addEventListener("wheel",e,{passive:!1}),t.addEventListener("touchstart",o,{passive:!0}),t.addEventListener("touchmove",r,{passive:!1}),()=>{t.removeEventListener("wheel",e),t.removeEventListener("touchstart",o),t.removeEventListener("touchmove",r)}}function li(t,e,n,i){let o=t instanceof Element?t:null;for(;o;){if(i!==0&&Vo(o,i)||n!==0&&Ko(o,n))return!0;if(o===e)break;o=o.parentElement}return!1}var di=/^(auto|scroll|overlay)$/;function Vo(t,e){return t.scrollHeight<=t.clientHeight||!di.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function Ko(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!di.test(n.overflowX))return!1;let i=Math.abs(t.scrollLeft),o=t.scrollWidth-t.clientWidth;return(n.direction==="rtl"?e<0:e>0)?i<o-1:i>0}var ci=new WeakMap,ui=new WeakSet;function W(t,e,n){if(ci.set(t,n),ui.has(t))return;ui.add(t);let i=()=>ci.get(t),o=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&t.contains(s)?s:null};e.onClick&&t.addEventListener("click",r=>{let s=o(r.target);s&&e.onClick?.(s,i(),r)}),e.onEnter&&t.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,i())},!0),e.onLeave&&t.addEventListener("mouseleave",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onLeave?.(s,i())},!0),e.preventMousedown&&t.addEventListener("mousedown",r=>r.preventDefault())}function q(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function $(t){t.offsetWidth}var Yo={selectedIso:null,selectedRange:null,rangeStart:null};function ye(t){if(!w(t.activeFormatType))return Yo;let e=t.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?ue(i,o):null,rangeStart:t.dateRangeStart}}let n=pe(t.editingParam);return{selectedIso:n?null:ct(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function Bt(t){return t.pendingStart?ue(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function Wt(t,e){if(t==null)return{selected:!1,inRange:!1};let{selectedIso:n,range:i}=e,o=t===n||i!=null&&(t===i.start||t===i.end),r=i!=null&&t>i.start&&t<i.end;return{selected:o,inRange:r}}var pi="data-aia-key";function G(t,e,n){let i=new Map;for(let s of Array.from(t.children)){let a=s.getAttribute(pi);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=n.keyOf(a,s);o.add(l);let d=i.get(l);d||(d=n.create(a,s),d.setAttribute(pi,l)),n.update?.(d,a,s),t.children[s]!==d&&t.insertBefore(d,t.children[s]??null),r.push(d)}for(let[s,a]of i)o.has(s)||a.remove();return r}function mi(t,e){if(!e.interactive)return null;let n=e.options[q(t)];return n?.is_tappable?n:null}var Qo={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(t,e)=>{if(t.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(t.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let n=mi(t,e);n&&(t.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&mi(t,e)&&e.callbacks.onHighlight(q(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,q(t))}};function gi(t,e,n,i,o,r,s,a=!0){let l=t.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){l?.remove();return}if(!l){l=zo(),t.appendChild(l),$(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}W(l,Qo,{options:e,callbacks:s,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=st(o));let c=l.querySelector(".magicx-aia-datepicker-grid");c&&Xo(c,e,n,i,r)}function Xo(t,e,n,i,o){let r=k(new Date),s=Bt({pendingStart:o.rangeStart,highlightedIso:N(e[n]),selected:o.selectedRange});G(t,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>jo(a),update:(a,l,d)=>{let c=N(l),u=Wt(c,{selectedIso:o.selectedIso,range:s}),m=d===n&&l.is_tappable;a.id=`${i}-option-${d}`,a.dataset.aiaIndex=String(d),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function jo(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=ut(t);if(n==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",t.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(n),e.appendChild(i),e}function zo(){let t=document.createElement("div");t.className="magicx-aia-datepicker",t.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let n=document.createElement("span");n.className="magicx-aia-datepicker-month",n.setAttribute("data-aia-date-month",""),n.setAttribute("aria-live","polite"),e.append(fi("prev","Previous month","\u2039"),n,fi("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of Ee){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,i.appendChild(s)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),t.append(e,i,o),t}function fi(t,e,n){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${t}`,""),i.setAttribute("aria-label",e),i.textContent=n,i.disabled=!0,i}var Jo={itemSelector:"[data-aia-pill]",onClick:(t,e)=>{if(e.loading||t.disabled)return;let n=Number.parseInt(t.dataset.aiaPillIndex??"-1",10);n>=0&&e.onSelectPill(n)},preventMousedown:!0},hi=[125,69];function bi(t,e){return e?1:t===0?.7:t===1?.4:.2}function ze(t,e,n,i,o=!1,r=!1,s=!1){let a=t.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",t.appendChild(a)),W(a,Jo,{onSelectPill:i,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<hi.length;l++){let d=hi[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(bi(l,!1)),a.appendChild(c)}return}r?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();G(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=l.text,d.disabled=!0,d},update:(l,d,c)=>{let u=l,m=s&&c===n&&!r,f=["magicx-aia-pill"];o&&f.push("magicx-aia-pill--rounded"),r&&f.push("magicx-aia-pill--skeleton"),u.className=f.join(" "),u.style.width="",u.style.opacity=String(bi(c,m)),u.dataset.aiaPillIndex=String(c),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),$(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function qt(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Zo=32;function yi(t,e){if(e.ctrlKey)return null;let n=e.deltaY||0,i=e.deltaX||0;if(!n||Math.abs(i)>=Math.abs(n))return null;let o=t.scrollWidth-t.clientWidth;if(o<=1)return null;let r=t.scrollLeft,s=n;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=t.clientWidth),Math.max(0,Math.min(o,r+s))}function $t(t){let e=n=>{let i=yi(t,n);i!==null&&(n.preventDefault(),t.scrollLeft=i)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var Si=Intl.Segmenter,xi=Si?new Si(void 0,{granularity:"grapheme"}):null;function Gt(t){let e=t.trim().normalize("NFC").toUpperCase();if(xi)for(let n of xi.segment(e))return n.segment;return Array.from(e)[0]??"?"}var Ut=new WeakMap,vi=new WeakMap,er="Products";function Ei(t,e,n,i,o,r="row",s="image"){let a=t.querySelector(".magicx-aia-products");if(e.length===0){a?.remove();return}if(!a){a=document.createElement("section"),a.className="magicx-aia-products",a.setAttribute("data-aia-products",""),a.setAttribute("role","group"),a.setAttribute("aria-labelledby",`${n}-products-label`);let d=document.createElement("div");d.className="magicx-aia-products-label",d.id=`${n}-products-label`,d.setAttribute("data-aia-products-label",""),d.textContent=er;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),$t(c),a.append(d,c),t.appendChild(a)}a.setAttribute("data-aia-products-layout",r);let l=a.querySelector(".magicx-aia-products-row");if(l){G(l,e,{keyOf:d=>nr(d),create:d=>ir(d,i,o,s),update:(d,c,u)=>{d.id=`${n}-product-${u}`,d.dataset.aiaIndex=String(u),vi.get(d)?.(s)}}),$(l);for(let d of l.querySelectorAll("[data-aia-product]")){let c=Ut.get(d);c&&(Ut.delete(d),c())}}}function Vt(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let i of n)i.tabIndex=e?0:-1}var tr="Sold out";function nr(t){return[t.id,t.title,t.url,t.imageUrl,t.price,t.vendor,t.available===!1?"sold-out":""].map(e=>e??"").join("\0")}function ir(t,e,n,i){let o=document.createElement("a");o.className="magicx-aia-product",o.setAttribute("data-aia-product",""),o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.tabIndex=0;let r=document.createElement("span");r.className="magicx-aia-product-media",r.setAttribute("aria-hidden","true");let s=t.imageUrl?.trim(),a=!!s,l=()=>{r.replaceChildren(),r.toggleAttribute("data-aia-product-placeholder",i==="image"),r.toggleAttribute("data-aia-product-initial",i==="initial"),i==="initial"&&(r.textContent=Gt(t.title))};if(vi.set(o,u=>{u!==i&&(i=u,a||l())}),s){let u=document.createElement("img");u.onerror=()=>{a=!1,l()},u.className="magicx-aia-product-image",u.src=s,u.alt="",u.loading="lazy",u.decoding="async",r.appendChild(u)}else l();o.appendChild(r);let d=document.createElement("span");if(d.className="magicx-aia-product-body",t.vendor){let u=document.createElement("span");u.className="magicx-aia-product-vendor",u.textContent=t.vendor,d.appendChild(u)}let c=document.createElement("span");if(c.className="magicx-aia-product-title",c.textContent=t.title,d.appendChild(c),t.price){let u=document.createElement("span");u.className="magicx-aia-product-price",u.textContent=t.price,d.appendChild(u)}if(t.available===!1){o.setAttribute("data-aia-product-sold-out","");let u=document.createElement("span");u.className="magicx-aia-product-badge",u.textContent=tr,d.appendChild(u)}return o.appendChild(d),Ut.set(o,()=>{t.url&&(o.href=t.url),o.addEventListener("click",u=>{u.metaKey||u.ctrlKey||u.shiftKey||u.altKey||u.button!==0||(u.preventDefault(),e(t))})}),o.addEventListener("keydown",u=>{u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),e(t))}),o.addEventListener("focus",()=>n(!0)),o.addEventListener("blur",u=>{u.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),o}var or=80,rr=150,sr=280,ar=16,Kt="--aia-option-enter-delay";function Yt(t,e,n,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,t)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,n)/o));return Math.max(0,s-1-r)*80}function Qt(t,e){let n=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,t)/n))-1)*80+280}function U(t){if(!t)return null;let e=t.trim();if(e==="")return null;let n;try{n=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.href}function Se(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var wi={one:"item",other:"items"};function lr(t,e=wi){let n=Se(t);if(n===null)return null;let i=typeof e=="string"?e:t===1?e.one:e.other;return i===""?n:`${n} ${i}`}function dr(t){return U(t.image_url)!==null}var Pi="http://www.w3.org/2000/svg",cr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function ur(t,e){let n=t.toLowerCase();return n.startsWith("on")||n.includes("href")||n==="style"||n==="xml:base"||n==="id"||n==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var pr=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],mr=/^[a-zA-Z0-9#.,%\s()-]+$/;function fr(t){let e=[];for(let n of pr){let i=t.getAttribute(n);i===null||!mr.test(i)||/url\s*\(/i.test(i)||e.push(`${n}: ${i.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function Ti(t){for(let e of Array.from(t.attributes))ur(e.name,e.value)&&t.removeAttribute(e.name);fr(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!cr.has(n.localName)||n.namespaceURI!==Pi?n.remove():Ti(n)}else e.remove()}function xe(t){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(t,"image/svg+xml"),n=e.documentElement;return!n||n.localName!=="svg"||n.namespaceURI!==Pi||e.getElementsByTagName("parsererror").length>0?null:(Ti(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function Xt(t){return t.text}var Ci=new WeakMap;function gr(t,e,n){let i=e.length,o=kt(),r=Ci.get(t),s=n&&r&&_t(r.options,e)?r.plan:null,a=!s&&!n&&Rt(i,o)?Mt(t):null,l=s??Dt(i,o,a?.rowWidths??null,a?.gridWidth??null);return n||Ci.set(t,{options:e,plan:l}),t.style.gridTemplateColumns=l.template,t.style.setProperty("--aia-grid-max-height",l.maxHeight),t.querySelectorAll("[data-aia-option]").forEach((d,c)=>{d.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(c))}),l.cols}function Ii(t,e){if(e.loading||!e.interactive)return null;let n=e.options[q(t)];return n?.is_tappable?n:null}var hr={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=Ii(t,e);n&&(t.classList.add("magicx-aia-option--pressed"),e.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(t,e)=>{Ii(t,e)&&e.onHighlight(q(t))},onLeave:(t,e)=>e.onHighlight(-1,q(t))};function Oi(t,e,n,i,o,r,s,a="",l="below",d=!0,c=!0,u=!0,m=!0){let f=t.querySelector(".aia-grid");if(e.length===0){f?.remove();return}f||(f=document.createElement("div"),f.className="aia-grid magicx-aia-grid",f.setAttribute("data-scroll",""),f.style.setProperty("--aia-grid-min","250px"),f.style.setProperty("--aia-grid-max","1fr"),f.style.setProperty("--aia-grid-gap","0"),t.appendChild(f)),W(f,hr,{options:e,onSelect:i,onHighlight:o,loading:s,interactive:m});let h=f.dataset.aiaGroup!==a;f.dataset.aiaGroup=a,br(f,e,n,r,s,{showIcons:d,showImages:c,showCounts:u});let S=gr(f,e,s);yr(f,e.length,S,s,l),h&&(f.scrollTop=0)}function br(t,e,n,i,o,r){let s=o?"1":"0",a=t.dataset.aiaGroup??"",{showIcons:l,showImages:d,showCounts:c}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=d?h=>U(h.image_url)??"":()=>"",f=c?h=>Se(h.item_count)??"":()=>"";G(t,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${f(h)}\0${s}\0${a}`,create:(h,S)=>{let x=Sr(h,o,r);return o||(x.dataset.aiaEntering=""),x},update:(h,S,x)=>{let g=x===n&&!o;h.id=`${i}-option-${x}`,h.dataset.aiaIndex=String(x),h.setAttribute("aria-selected",String(g)),h.classList.toggle("magicx-aia-option--highlighted",g)}})}function yr(t,e,n,i,o){for(let r of t.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Kt,`${Yt(s,n,e,o)}ms`)}delete r.dataset.aiaEntering}}function Sr(t,e,{showIcons:n,showImages:i,showCounts:o}){let r=document.createElement("div");r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),e&&r.setAttribute("data-aia-loading",""),r.tabIndex=e||!t.is_tappable?-1:0;let s=["magicx-aia-option"];t.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),r.className=s.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=i?U(t.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.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"),f.onerror=()=>{f.hidden=!0},f.src=l,m.appendChild(f),a.appendChild(m),r.dataset.aiaImage=""}let d=!l&&n&&t.icon_svg?xe(t.icon_svg):null;if(d){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=d,a.appendChild(m),t.icon&&(r.dataset.aiaIcon=t.icon)}let c=document.createElement("span");if(c.className="magicx-aia-option-text",c.textContent=Xt(t),a.appendChild(c),t.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=t.tag,a.appendChild(m)}let u=o?Se(t.item_count):null;if(u!==null){let m=document.createElement("span");m.className="magicx-aia-option-count",m.textContent=u,a.appendChild(m),r.dataset.aiaItemCount=String(t.item_count)}return r.appendChild(a),r}var Ai="magicx-aia-scroll-arrow",Li="data-aia-scroll-arrow",de="data-aia-visible",Ri=1e3,Di=160,Mi="--aia-scroll-arrow-bottom",ki="Scroll down for more options",xr="[data-aia-products-label]",vr=4,Er=8,wr=240;function Pr(t,e,n,i){let o=t.scrollTop,r=n?.requestAnimationFrame,s=t.ownerDocument?.visibilityState==="hidden";if(!r||s||jt(t)){t.scrollTop=o+e,i();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),d=()=>{let c=Math.min(1,(l()-a)/wr),u=1-(1-c)*(1-c);t.scrollTop=o+e*u,c<1?r.call(n,d):i()};r.call(n,d)}function Tr(t=document){let e="http://www.w3.org/2000/svg",n=t.createElementNS(e,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("width","18"),n.setAttribute("height","18"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=t.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),n.appendChild(i),n}function _i(t=document){let e=t.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Ai,e.setAttribute(Li,""),e.setAttribute("aria-label",ki),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(Tr(t)),e}function Cr(t){let e=t.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function jt(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function zt({dropdown:t,grid:e,button:n}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1;n.disabled=!0;let r=null,s=null,a=null,l=null,d=p=>{if(p){if(n.hasAttribute(de))return;if(n.setAttribute(de,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),jt(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!o&&n.hasAttribute(de)&&(n.disabled=!1)},Ri)}else n.removeAttribute(de),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},c=p=>{let b=0,y=p;for(;y&&y!==t;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=t.querySelector(xr),b;if(p){let y=c(p)+p.offsetHeight/2;b=t.clientHeight-y-n.offsetHeight/2}else{let y=c(e),v=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;b=t.clientHeight-(y+e.offsetHeight)+(v>0?0:Er)}n.style.setProperty(Mi,`${Math.max(0,Math.round(b))}px`)},m=()=>{if(o||s!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,b=e.scrollHeight-e.clientHeight-e.scrollTop;d(!p&&b>vr)},f=()=>{if(o)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,d(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=jt(e)?0:Qt(b,Cr(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{o||s!==null||(d(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},Di))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),x=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-p);Pr(e,b,i,h)};n.addEventListener("mousedown",S),n.addEventListener("click",x);let g=null;return i&&typeof i.ResizeObserver=="function"&&(g=new i.ResizeObserver(()=>{u(),m()}),g.observe(e)),f(),{update:f,destroy(){o||(o=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,n.disabled=!0,e.removeEventListener("scroll",h),n.removeEventListener("mousedown",S),n.removeEventListener("click",x),g?.disconnect(),n.removeAttribute(de),n.setAttribute("aria-hidden","true"))}}}var Ir=[159,119,164];function Ze(t){let e=document.createElement("div");return e.id=t,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",n=>n.preventDefault()),Ht(e),e}var Je=new WeakMap;function Or(t,e){let n=Je.get(t);if(n||(n={button:_i(t.ownerDocument),grid:null,controller:null},t.appendChild(n.button),Je.set(t,n)),n.grid!==e&&(n.controller?.destroy(),n.controller=null,n.grid=e,e)){n.controller=zt({dropdown:t,grid:e,button:n.button});return}n.controller?.update()}function Jt(t){let e=Je.get(t);e&&(e.controller?.destroy(),Je.delete(t))}function et(t,e){let{filteredOptions:n,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:m}=e,f=s.length>0,h=a&&f,S=n.length>0,x=e.products.length>0,g=o&&(S||h||r||x);if(g?t.classList.add("magicx-aia-dropdown--visible"):t.classList.remove("magicx-aia-dropdown--visible"),r?t.setAttribute("data-aia-loading",""):t.removeAttribute("data-aia-loading"),!g){Vt(t,!1);return}x?t.setAttribute("data-aia-has-products",""):t.removeAttribute("data-aia-has-products"),t.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let p=t.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),t.appendChild(p));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=h||r&&a||b,v=p.querySelector(".magicx-aia-pill-bar");if(y){v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar aia-cluster",v.setAttribute("data-nowrap",""),v.setAttribute("data-aia-pillbar",""),p.insertBefore(v,p.firstChild));let M=v.querySelector(".magicx-aia-pill-scroll");M||(M=document.createElement("span"),M.className="magicx-aia-pill-scroll",M.setAttribute("data-aia-pill-scroll",""),v.insertBefore(M,v.firstChild)),ze(M,a?s:[],0,u,!0,r&&a,l),Rr(v,b,r||e.skipDisabled,s[0],m)}else v&&v.remove();let E=e.suggestions[0],P=E?`${E.type} ${E.text}`:"",L=w(e.formatType),T=L&&!r;Oi(p,L?[]:n,i,d,c,e.listboxId,r,P,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Or(t,p.querySelector(".aia-grid")),gi(p,T?n:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let I=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||L)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let M of Ir){let Z=document.createElement("span");Z.className="magicx-aia-skeleton-bar",Z.style.width=`${M}px`,I.appendChild(Z)}p.appendChild(I)}}else I&&I.remove();Ei(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),Vt(t,!0);let V=p.querySelector(".magicx-aia-footer")??Mr(),D=i>=0&&!!n[i]?.is_tappable;Dr(V,Ft(D,e.isInputEmpty)),V.isConnected||p.appendChild(V),Ar(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Ar(t,e){let n=e.map(i=>t.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<n.length;i++)t.children[i]!==n[i]&&t.insertBefore(n[i],t.children[i]??null)}var Lr={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function Rr(t,e,n,i,o){W(t,Lr,{onSkip:o,loading:n});let r=t.querySelector(".magicx-aia-skip");if(!e){r?.remove();return}r||(r=document.createElement("button"),r.type="button",r.tabIndex=-1,r.className="magicx-aia-skip",r.setAttribute("data-aia-skip",""),r.textContent="skip",r.disabled=!0,t.appendChild(r),$(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=n}function Dr(t,{key:e,hint:n}){let i=t.querySelector(".magicx-aia-footer-key"),o=t.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==n&&(o.textContent=n))}function Mr(){let t=document.createElement("footer");t.className="magicx-aia-footer",t.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let n=document.createElement("div");n.className="aia-cluster magicx-aia-footer-hint-group",n.setAttribute("data-align","center"),n.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",n.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=Nt(),r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(n,r),t.append(e),t}function Ni(t,e){let n=Ze(e.listboxId);return t.appendChild(n),{dropdown:n}}function Zt(t,e,n){let i=ye(e);et(t.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:K(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.dropdownSuggestion??e.actionableSuggestions[0]?[{...e.dropdownSuggestion??e.actionableSuggestions[0],options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:n.selectOption,onHighlight:(o,r)=>{r!==void 0&&n.store.get().activeDropdownIndex!==r||n.store.set({activeDropdownIndex:o})},onPillClick:n.setActivePill,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:o=>n.store.set({isFocused:o})})}var kr=6,_r=.3;function Fi(t){return t<=0?"0px":`${(-Math.min(_r,2*kr/t)).toFixed(3)}px`}function en(t){let{input:e,segments:n,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=t,a=t.showChipIcons??!0,l=t.showChipImages??!0,d=n.length===0;e.dataset.aiaEmpty=d?"true":"false",ri(e,d?r:"");let c=n.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?U(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(c===u&&(i??"")===m&&(o??"")===f)return;if(c===u){e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";for(let p of e.querySelectorAll("strong[data-param-id]")){let b=p.dataset.paramId,y=p.dataset.seg==="completed"&&b===i;p.classList.toggle("magicx-aia-shimmer-revealed",y),p.classList.toggle("magicx-aia-shimmer-sweep",y),p.classList.toggle("magicx-aia-segment--editing",b===o)}return}let h=s?_(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let S=O(e),x=S.createDocumentFragment(),g=0;for(let p of n)if(g+=p.value.length,p.type==="completed"){let b=S.createElement("strong");b.dataset.seg="completed",b.dataset.paramId=p.param.id;let y=p.param.id===i,v=p.param.id===o,E=["magicx-aia-segment","magicx-aia-segment--completed"];y&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),v&&E.push("magicx-aia-segment--editing"),b.className=E.join(" "),b.style.letterSpacing=Fi(p.value.length);let P=l?U(p.param.image_url):null;if(P){let T=S.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${P}")`),b.appendChild(T),b.dataset.aiaImage=""}let L=!P&&a&&p.param.icon_svg?xe(p.param.icon_svg):null;if(L){let T=S.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=L,b.appendChild(T),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),x.appendChild(b)}else if(p.type==="identified"){let b=S.createElement("strong");b.dataset.seg="identified",b.dataset.paramId=p.param.id;let y=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===o&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=Fi(p.value.length),b.textContent=p.value,x.appendChild(b)}else x.appendChild(S.createTextNode(p.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(g),h!=null?A(e,Math.max(0,Math.min(h,g))):s&&Kn(e)&&A(e,g)}var Nr='<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 Hi(){let t=document.createElement("button");return t.type="button",t.className="magicx-aia-submit",t.setAttribute("aria-label","Submit"),t.setAttribute("data-aia-submit",""),t.innerHTML=Nr,t}function Fr(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function Bi(t,e){let n=e.firstElementChild;if(!n){e.removeAttribute("data-aia-pill-wrapped");return}let i=n.getBoundingClientRect(),o=t.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Wi(t,e){let{listboxId:n}=e,i=Ze(n);t.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),t.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",Fr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",n),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=Hi(),o.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),d.setAttribute("data-aia-submit-slot",""),o.appendChild(d));let c=new AbortController,{signal:u}=c,m=!1,f=0,h=()=>{let g=We(s),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=B(s)?.node??null;if(!g||!s.contains(g))return null;let y=(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&Vn(s,y)?null:y};if(o.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(f=performance.now(),h(),e.handleCaretAfterInput(_(s)))},{signal:u}),O(s).addEventListener("selectionchange",()=>{let g=B(s);if(!g||!s.contains(g.node))return;let p=g.collapsed?S():null,b=e.store.get(),y=b.editingParam?.id??b.editingIdentified?.id??null;if(p&&p!==y){e.startEditingParam(p);return}performance.now()-f<50||e.handleCaretMove(_(s))},{signal:u}),s.addEventListener("click",g=>{let p=Et(s,g.target);p&&(e.startEditingParam(p),wt(s,p))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",g=>{let p=g,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){g.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(y)&&g.preventDefault()}},{signal:u}),s.addEventListener("paste",g=>{g.preventDefault();let p=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=O(s),y=_e(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let v=b.createTextNode(p);y.insertNode(v),y.setStartAfter(v),he(s,y.startContainer,y.startOffset),h()},{signal:u}),s.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",g=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(J(p.text,p.completedParams,p.skippedParams,{identifiedParams:p.identifiedParams,isReady:p.isReady,customFields:p.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let g=B(s);(!g||!s.contains(g.node))&&he(s,s,0)}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>Bi(s,a));g.observe(s),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:c}}function tn(t,e,n){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=t,{pillPlacement:a,setActivePill:l,selectOption:d,store:c}=n;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${n.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let g=!!e.text||e.completedParams.length>0;s.disabled=!g}let m=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==m;if(en({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:n.showChipIcons??!0,showChipImages:n.showChipImages??!0}),a==="inline"){let g=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;g||e.actionableSuggestions.length>0?ze(o,e.actionableSuggestions,0,l,!1,g,e.isActivePillSelected):qt(o)}else qt(o);Bi(i,o),f?(i.focus(),A(i,e.caretOffset??e.text.length)):e.isFocused&&We(i)!==e.text&&A(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:K(e.editingIdentified.type),required:!0,options:[]}:null,S=e.dropdownSuggestion??h??e.actionableSuggestions[0],x=ye(e);et(r,{suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:x.selectedIso,selectedDateRange:x.selectedRange,dateRangeStart:x.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:d,onHighlight:(g,p)=>{p!==void 0&&c.get().activeDropdownIndex!==p||c.set({activeDropdownIndex:g})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:g=>c.set({isFocused:g})})}function nn(t){let e=t,n=new Set,i=[],o=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},i.push([e,a]),!o){o=!0;try{let l=0;for(let d=i.shift();d;d=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,u]=d;for(let m of n)m(c,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(n.add(r),()=>{n.delete(r)})}}function qi(t,e){let n,i,o=r=>(r!==n&&(n=r,i=e(r)),i);return{get:()=>{let r=t.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?t.set(s=>{let a={...s,...o(s)};return r(a)}):t.set(r)},peek:r=>{let s={...t.get(),...r};return{...s,...e(s)}},subscribe:r=>t.subscribe((s,a)=>{let l={...a,...o(a)},d={...s,...o(s)};r(d,l)})}}var on=new WeakSet,$i=new WeakMap;function Ui(t){return t.nodeType===Node.DOCUMENT_NODE}function Hr(t){return Ui(t)?t:t.ownerDocument}function Br(t){let e=$i.get(t);if(e)return e;let n=t.defaultView?.CSSStyleSheet;if(typeof n!="function")return null;try{let i=new n;return typeof i.replaceSync!="function"?null:(i.replaceSync(Ki),$i.set(t,i),i)}catch{return null}}function Gi(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Ki,e.appendChild(n)}function Vi(t){if(typeof document>"u")return;let e=t??document;if(on.has(e))return;let n=Hr(e);if(Ui(e)){let r=e.head??e.documentElement;if(!r)return;Gi(n,r),on.add(e);return}let i=Br(n),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):Gi(n,e),on.add(e)}var Ki=`.aia-stack {
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--aia-stack-space, 0.5rem);
@@ -666,6 +666,8 @@ function it(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
666
666
  text-decoration: none;
667
667
  cursor: pointer;
668
668
  transition: background-color 150ms ease;
669
+ /* The sold-out badge is positioned against the card. */
670
+ position: relative;
669
671
  }
670
672
 
671
673
  .magicx-aia-product:hover {
@@ -781,6 +783,39 @@ function it(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
781
783
  );
782
784
  }
783
785
 
786
+ /* Sold-out badge. It sits last in the text column, so the card's accessible
787
+ name ends with it, and is lifted over the image's top-left corner: card
788
+ padding (6px) plus the same again. A light chip with dark, tracked capitals
789
+ reads on any photo, light or dark, and on either panel surface. */
790
+ .magicx-aia-product-badge {
791
+ position: absolute;
792
+ top: var(--aia-product-badge-inset, 12px);
793
+ left: var(--aia-product-badge-inset, 12px);
794
+ padding: 3px 6px;
795
+ border-radius: 4px;
796
+ background: var(--aia-product-badge-bg, rgba(255, 255, 255, 0.94));
797
+ color: var(--aia-product-badge-color, #1f2328);
798
+ /* A hairline ring keeps the chip's edge on a pale image or a light panel. */
799
+ box-shadow:
800
+ 0 0 0 1px rgba(0, 0, 0, 0.08),
801
+ 0 1px 2px rgba(0, 0, 0, 0.18);
802
+ font-family: inherit;
803
+ font-size: var(--aia-product-badge-font-size, 9px);
804
+ font-weight: 600;
805
+ line-height: 1;
806
+ letter-spacing: 0.08em;
807
+ text-transform: uppercase;
808
+ white-space: nowrap;
809
+ pointer-events: none;
810
+ }
811
+
812
+ /* A sold-out product's image steps back, so the badge is not the only cue.
813
+ Desaturated rather than faded: opacity lets the panel show through, which
814
+ muddies a photo on a dark surface. */
815
+ .magicx-aia-product[data-aia-product-sold-out] .magicx-aia-product-image {
816
+ filter: grayscale(0.55);
817
+ }
818
+
784
819
  /* --- List layout (\`productsLayout: "list"\`) ---
785
820
  The same cards stacked as full-width rows \u2014 thumbnail on the left, text on
786
821
  the right \u2014 for results that read as a list (courses, listings, documents)
@@ -818,6 +853,27 @@ function it(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
818
853
  flex: 1 1 auto;
819
854
  }
820
855
 
856
+ /* In a list the badge is a banner across the bottom of the thumbnail. The
857
+ thumbnail is centred in the card and the card's top and bottom padding
858
+ match, so its bottom edge is half a thumbnail below the card's centre; its
859
+ left edge is the card's 8px inline padding. */
860
+ .magicx-aia-products[data-aia-products-layout="list"] .magicx-aia-product-badge {
861
+ top: calc(50% + var(--aia-product-list-media-size, 44px) / 2);
862
+ left: 8px;
863
+ width: var(--aia-product-list-media-size, 44px);
864
+ transform: translateY(-100%);
865
+ padding: 2px 0;
866
+ border-radius: 0 0 8px 8px;
867
+ /* A dark scrim rather than the light chip: a light banner at a tile's edge
868
+ merges with a light panel and reads as a cropped photo. */
869
+ background: var(--aia-product-badge-list-bg, rgba(17, 17, 17, 0.72));
870
+ color: var(--aia-product-badge-list-color, #fff);
871
+ box-shadow: none;
872
+ font-size: var(--aia-product-badge-list-font-size, 7px);
873
+ letter-spacing: 0.02em;
874
+ text-align: center;
875
+ }
876
+
821
877
  /* --- "More below" scroll arrow (see render/scrollArrow.ts) ---
822
878
  A bare down chevron at the bottom-centre of the option list, shown while
823
879
  there is more to scroll to \u2014 no disc, border or shadow around it. It rests
@@ -2183,5 +2239,5 @@ function it(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
2183
2239
  background: var(--aia-surface, #ffffff);
2184
2240
  }
2185
2241
  }
2186
- `;var et=class{constructor(){this.reported=new Set}run(e,n){try{return n()}catch(i){this.report(e,i,e);return}}runListener(e,n,i=e){try{return n(),!0}catch(o){return this.report(e,o,i),!1}}report(e,n,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,n))}};var tt=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,n){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>n(...s);this.keys.set(o,i);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...n){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...n),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var nt=class{constructor(){this.timers=new Map}schedule(e,n,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),n()},i);this.timers.set(e,o)}clear(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var xe=class{constructor(e,n="auto",i){this.container=e;this.mode=n;this.onResolve=i;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 Lr=6e4;function Dr(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function Mr(t){return(t??Te).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function kr(t){return pe(t)?`Bearer ${await Ce(t).getToken()}`:Oe(t)}async function Gi(t){try{let e=Mr(t.apiConfig?.endpoint),n=Ie(t.apiConfig),i=await kr(t.apiConfig);i&&(n.Authorization=i);let o=JSON.stringify({source:t.source,session_id:t.sessionId,...t.visitorId&&{visitor_id:t.visitorId},...t.requestId&&{request_id:t.requestId},type:t.type,at:new Date().toISOString(),query_data:t.queryData});await fetch(e,{method:"POST",headers:n,body:o,...t.keepalive&&Dr(o)<=Lr&&{keepalive:!0}})}catch{}}var _r=50,Nr=new Set(["search_started","submit","product_click","impression"]),Fr="newParam",$i="suggestionRemoval",Hr="selectionAnimation",Jt="skeletonExit",Br=650,Wr=0;function qr(){return`:ac-${++Wr}:`}var Vi=170,Gr=100;function Ui(){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 Zt=class{constructor(e,n={}){this.inputStore=jt(Ui());this._listboxId=qr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new nt;this.boundary=new et;this.subscriberCount=0;this.emitter=new tt(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;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=n,this.renderMode=n.renderMode??"full",this.store=Ni(this.inputStore,i=>Xn(i,this.opts)),n.onSubmit&&this.emitter.on("submit",n.onSubmit),n.onResult&&this.emitter.on("result",n.onResult),n.onError&&this.emitter.on("error",n.onError),n.onChange&&this.emitter.on("change",n.onChange),n.onParamsChange&&this.emitter.on("paramsChange",n.onParamsChange),n.onStateChange&&this.emitter.on("stateChange",n.onStateChange),n.onFocus&&this.emitter.on("focus",n.onFocus),n.onBlur&&this.emitter.on("blur",n.onBlur),n.onProductSelect&&this.emitter.on("productSelect",n.onProductSelect),n.value!==void 0&&this.store.set({text:n.value}),n.completedParams!==void 0&&this.store.set({completedParams:n.completedParams}),this.pillsController=new Ge(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new Qe({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new $e(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new qe(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Me(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,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:(i.options??[]).filter(s=>s.text!==o.text).map(s=>s.text)})},onResponse:({requestId:i,funnelTelemetry:o})=>{this.lastRequestId=i,this.funnelTelemetry=o,this.pendingSearchStarted&&(this.pendingSearchStarted=!1,this.fireTelemetry("search_started",{})),this.fireImpression(),this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new We(this.store,{columns:n.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text&&!o.text&&this.searchStartedSessionId!==this.sessionId&&(this.searchStartedSessionId=this.sessionId,this.funnelTelemetry===null?this.pendingSearchStarted=!0:this.fireTelemetry("search_started",{})),i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.subscribeSkeletonMirror(),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:r,invalid:s}=De(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let r=i.editingIdentified;if(!r||i.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===r.anchor&&l.value===r.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...r,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let o=i.pendingRangeStart;!o||o.key===he(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let r=i.pendingSpan;if(!r||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let s=r.anchor;if(i.text!==o.text){let l=On(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||Cn(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(Wi(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({...Ui(),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&&(ti(this.domRefs.input),Kt(this.domRefs.dropdown)),this.dropdownRefs&&Kt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let n=this.store.get();if(n.editingIdentified&&e!==n.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let n=this.store.get().text.length;this.store.set({caretOffset:n,isFocused:!0}),this.scheduleSetCursor(n)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let n=0;for(let i of this.store.get().segments){let o=n;if(n+=i.value.length,i.type!=="text"&&e>o&&e<=n)return{kind:i.type,param:i.param,start:o,end:n}}return null}withoutChip(e,n){return n.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==n.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==n.param.id)}}removeParamAtCaret(e){let n=this.findChipSpanAt(e);if(!n)return!1;let{text:i}=this.store.get(),{start:o,end:r}=n;if(e===r){let{text:l,removed:d}=Ye(i,o,r);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>o?Math.max(o,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=St(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let n=this.findChipSpanAt(e);return!n||n.kind!=="completed"||n.end!==e?!1:(this.reEdit.start(n.param.id),this.store.get().editingParam?.id===n.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let n=this.domRefs;if(n)n.input.focus(),L(n.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let n=this.store.get();if(n.editingIdentified?.id===e)return!0;let i=n.identifiedParams.find(c=>c.id===e);if(!i)return!1;let o=Y(i);if(!w(o))return!1;let r=ie(i.text),s=o==="date-range"||r?"date-range":"date",a=0,l=-1;for(let c of n.segments){if(c.type!=="text"&&c.param.id===e){l=a;break}a+=c.value.length}if(l<0)return!1;let d=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:d,text:i.text,iso:r?r.start:ut(i),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}recordSubmit(e){this.fireTelemetry("submit",{query:e.query,completed_pills:e.completed_params.filter(n=>n.placeholder).map(n=>({key:n.type,value:n.text??""}))})}selectProduct(e){let n=this.store.get(),i=n.products.findIndex(r=>r.id===e.id),o=n.customFields?.items?.matched?.find(r=>r.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:n.text,product_id:e.id,...o&&{origin_id:o},position:i>=0?i+1:null}),this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let n=this.store.get();if(!w(n.activeFormatType)||!n.dateView)return;let i=at(n.dateView,e);this.store.set({dateViewMonth:{...i,key:he(n)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let n=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],r=i.slice(1),s=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...n,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.text}]}}),r.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let n=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),n)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return J(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,n){return this.emitter.on(e,n)}update(e){let n=this.opts.products,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==n||"showProducts"in e&&e.showProducts!==i)&&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)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let n=this.store.get();if(n.activeFormatType==="date-range"){let o=N(e);if(o){let r=n.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:he(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(gn(r,o));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(Jt),this.reEdit.selectOption(e);return}let i=jn(n,e);if(i){if(this.fireTelemetry("option",{raw_query:R(n.text,n.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:w(n.activeFormatType)?[]:i.telemetry.otherOptions}),this.timers.clear(Jt),this.store.set({...i.patch,...Ke(n)}),this.startSelectionAnimationTimer(),this.timers.clear($i),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule($i,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},Vi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Hr,()=>this.store.set({inSelectionAnimation:!1}),Vi)}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(),n=e.suggestions.filter(r=>r.type!=="placeholder").map(r=>({key:r.type,options:(r.options??[]).slice(0,_r).map(s=>s.text)})),i=e.products.map(r=>r.id);if(n.length===0&&i.length===0)return;let o=JSON.stringify([n,i]);o!==this.lastImpressionKey&&(this.lastImpressionKey=o,this.fireTelemetry("impression",{query:e.text,pills:n,product_ids:i}))}fireTelemetry(e,n){let i=this.funnelTelemetry===!0;if(!i&&Nr.has(e))return;let o=this.resolveSource();Gi({source:o,sessionId:this.sessionId,visitorId:i?this.resolveVisitorId():void 0,requestId:i?this.lastRequestId:null,keepalive:i,type:e,queryData:n,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),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 xe(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,n={store:this.store,listboxId:this.listboxId,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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=_i(this.container,n);let i=()=>{this.domRefs&&Xt(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Xt(this.domRefs,this.store.get(),n),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,n={store:this.store,listboxId:this.listboxId,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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Li(this.container,n);let i=()=>{this.dropdownRefs&&Yt(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Yt(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(Ve),i=()=>e();n.addEventListener("change",i),this.unsubscribers.push(()=>n.removeEventListener("change",i))}subscribeBatchedRender(e){let n=!1;this.unsubscribers.push(this.store.subscribe(()=>{n||(n=!0,queueMicrotask(()=>{n=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,n)=>{if(!e.skeletonOptions)return;if(!n.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!n.isLoading||e.isLoading)return;let i={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(i);return}this.timers.schedule(Jt,()=>this.store.set(i),Gr)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule(Fr,()=>this.store.set({newParamId:null}),Br)}))}handleChange(e){let n=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=Dn(e,n.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=H(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Tn(e.segments,n);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(r=>r.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let n=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,n);X(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:i}=R(e.text,e.completedParams);this.fetchController.doFetch(n,i)}commitIdentifiedDate(e){let n=this.store.get(),i=n.editingIdentified;if(!i)return;if(n.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=n.text.slice(0,i.anchor),r=n.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=r.length===0||r[0]!==" "?`${s} `:s,d=o+l+r,c=d.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:U(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:R(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:d,completedParams:[...n.completedParams,u],identifiedParams:n.identifiedParams.filter(m=>m.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let n=this.store.get();if(w(n.activeFormatType))return;let i=Ue({mode:"fresh",text:e,completedParams:n.completedParams,suggestions:n.suggestions,filterBase:n.filterBase,filterInProgress:n.filterInProgress});i&&this.store.set(i.patch)}};export{Zt as AIAutocomplete,ni as ATTRIBUTION_URL,ft as DATE_RANGE_META_END,mt as DATE_RANGE_META_START,yi as DEFAULT_OPTION_COUNT_UNIT,xe as ModeController,Ve as OPTIONS_GRID_MOBILE_QUERY,Wt as OPTION_ENTER_DELAY_VAR,jo as OPTION_ENTER_FADE_MS,zo as OPTION_ENTER_RISE_MS,Jo as OPTION_ENTER_RISE_PX,Xo as OPTION_ENTER_STAGGER_MS,ko as PLACEHOLDER_FADE_OUT_MS,se as PLACEHOLDER_LEAVING_ATTR,_o as PLACEHOLDER_SWAP_GAP_MS,Do as PLACEHOLDER_TYPE_MS,Mo as PLACEHOLDER_WORD_PAUSE_MS,Vn as PRODUCT_PATH_PREFIX,Uo as PRODUCT_ROW_PX_PER_LINE,mn as RANGE_SEPARATOR,Ti as SCROLL_ARROW_ATTR,Oi as SCROLL_ARROW_BOTTOM_VAR,Pi as SCROLL_ARROW_CLASS,Ci as SCROLL_ARROW_FADE_MS,Ai as SCROLL_ARROW_LABEL,Ii as SCROLL_ARROW_SCROLL_IDLE_MS,le as SCROLL_ARROW_VISIBLE_ATTR,yn as SKIPPED_PARAM_TEXT,ve as WEEKDAY_LABELS,at as addMonths,Nt as attachProductRowWheel,Ut as attachScrollArrow,Rt as buildAttributionUrl,lt as buildDateOptions,R as buildQuery,J as buildSubmitResult,ct as cellDay,N as cellIso,Kn as computeOptionsGridLayout,Dt as containScroll,jt as createStore,yt as cursorIsAtEnd,kt as dateCellMarks,be as dateSelectionFor,Be as extractPlainText,ne as formatAbsoluteDate,ln as formatDate,fn as formatDateRange,ye as formatOptionCount,_ as getCursorOffset,Lt as getFooterHint,U as identifiedParamLabel,w as isCalendarFormat,Ot as isOptionsGridMobileViewport,k as isoDate,It as measureOptionsGrid,rt as monthLabel,Tt as needsOptionsGridMeasurement,Zo as optionCountLabel,qt as optionEnterDelayMs,er as optionHasImage,$ as optionImageSrc,$t as optionLabel,Gt as optionsEntranceDurationMs,Pt as optionsGridTemplateColumns,Ee as parseDate,K as parseLooseDate,ie as parseLooseDateRange,bt as plainTextLength,Ct as planOptionsGrid,St as previousGraphemeBoundary,Un as productFromMatchedItem,Ft as productInitial,mi as productRowWheelTarget,Et as productsFromCustomFields,Qt as renderEditableContent,Y as resolveFormatType,ut as resolveIdentifiedDate,At as sameOptionRows,Se as sanitizeOptionIconSvg,ht as scrollCaretIntoView,dt as selectedIsoFromText,ue as selectedRangeFor,L as setCursorOffset,me as toWireIdentifiedParams,Mt as visibleDateRange,fe as withSkippedParams};
2242
+ `;var tt=class{constructor(){this.reported=new Set}run(e,n){try{return n()}catch(i){this.report(e,i,e);return}}runListener(e,n,i=e){try{return n(),!0}catch(o){return this.report(e,o,i),!1}}report(e,n,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,n))}};var nt=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,n){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>n(...s);this.keys.set(o,i);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...n){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...n),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var it=class{constructor(){this.timers=new Map}schedule(e,n,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),n()},i);this.timers.set(e,o)}clear(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ve=class{constructor(e,n="auto",i){this.container=e;this.mode=n;this.onResolve=i;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 Wr=50,qr=new Set(["search_started","submit","product_click","impression"]),$r="newParam",Yi="suggestionRemoval",Gr="selectionAnimation",rn="skeletonExit",Ur=650,Vr=0;function Kr(){return`:ac-${++Vr}:`}var Qi=170,Yr=100;function Xi(){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 sn=class{constructor(e,n={}){this.inputStore=nn(Xi());this._listboxId=Kr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new it;this.boundary=new tt;this.subscriberCount=0;this.emitter=new nt(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;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=n,this.renderMode=n.renderMode??"full",this.store=qi(this.inputStore,i=>Zn(i,this.opts)),n.onSubmit&&this.emitter.on("submit",n.onSubmit),n.onResult&&this.emitter.on("result",n.onResult),n.onError&&this.emitter.on("error",n.onError),n.onChange&&this.emitter.on("change",n.onChange),n.onParamsChange&&this.emitter.on("paramsChange",n.onParamsChange),n.onStateChange&&this.emitter.on("stateChange",n.onStateChange),n.onFocus&&this.emitter.on("focus",n.onFocus),n.onBlur&&this.emitter.on("blur",n.onBlur),n.onProductSelect&&this.emitter.on("productSelect",n.onProductSelect),n.value!==void 0&&this.store.set({text:n.value}),n.completedParams!==void 0&&this.store.set({completedParams:n.completedParams}),this.pillsController=new Ge(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new Xe({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Ue(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new $e(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new ke(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,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{let s=i.options??[];this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:s.filter(a=>a.text!==o.text).map(a=>a.text),key:i.type,position:se(s,o.text)})},onResponse:({requestId:i,funnelTelemetry:o})=>{this.lastRequestId=i,this.funnelTelemetry=o,this.pendingSearchStarted&&(this.pendingSearchStarted=!1,this.fireTelemetry("search_started",{})),this.fireImpression(),this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new qe(this.store,{columns:n.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.subscribeSkeletonMirror(),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:r,invalid:s}=Me(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let r=i.editingIdentified;if(!r||i.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===r.anchor&&l.value===r.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...r,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let o=i.pendingRangeStart;!o||o.key===be(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let r=i.pendingSpan;if(!r||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let s=r.anchor;if(i.text!==o.text){let l=kn(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||Dn(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(Vi(this.opts.styleRoot??z(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({...Xi(),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&&(si(this.domRefs.input),Jt(this.domRefs.dropdown)),this.dropdownRefs&&Jt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}prefillText(e){this.applyTextChange(e,!1)}noteSearchStarted(){this.searchStartedSessionId!==this.sessionId&&(this.searchStartedSessionId=this.sessionId,this.funnelTelemetry===null?this.pendingSearchStarted=!0:this.fireTelemetry("search_started",{}))}setValue(e){let n=this.store.get();if(n.editingIdentified&&e!==n.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let n=this.store.get().text.length;this.store.set({caretOffset:n,isFocused:!0}),this.scheduleSetCursor(n)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let n=0;for(let i of this.store.get().segments){let o=n;if(n+=i.value.length,i.type!=="text"&&e>o&&e<=n)return{kind:i.type,param:i.param,start:o,end:n}}return null}withoutChip(e,n){return n.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==n.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==n.param.id)}}removeParamAtCaret(e){let n=this.findChipSpanAt(e);if(!n)return!1;let{text:i}=this.store.get(),{start:o,end:r}=n;if(e===r){let{text:l,removed:d}=Qe(i,o,r);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>o?Math.max(o,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=Tt(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let n=this.findChipSpanAt(e);return!n||n.kind!=="completed"||n.end!==e?!1:(this.reEdit.start(n.param.id),this.store.get().editingParam?.id===n.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let n=this.domRefs;if(n)n.input.focus(),A(n.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let n=this.store.get();if(n.editingIdentified?.id===e)return!0;let i=n.identifiedParams.find(c=>c.id===e);if(!i)return!1;let o=Q(i);if(!w(o))return!1;let r=ie(i.text),s=o==="date-range"||r?"date-range":"date",a=0,l=-1;for(let c of n.segments){if(c.type!=="text"&&c.param.id===e){l=a;break}a+=c.value.length}if(l<0)return!1;let d=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:d,text:i.text,iso:r?r.start:pt(i),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}recordSubmit(e){this.fireTelemetry("submit",{query:e.query,completed_pills:e.completed_params.filter(n=>n.placeholder).map(n=>({key:n.type,value:n.text??""}))})}selectProduct(e){let n=this.store.get(),i=n.products.findIndex(r=>r.id===e.id),o=n.customFields?.items?.matched?.find(r=>r.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:n.text,product_id:e.id,...o&&{origin_id:o},position:i>=0?i+1:null}),this.emitter.emit("productSelect",e)}handleTextChange(e){this.applyTextChange(e,!0)}applyTextChange(e,n){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,n)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let n=this.store.get();if(!w(n.activeFormatType)||!n.dateView)return;let i=lt(n.dateView,e);this.store.set({dateViewMonth:{...i,key:be(n)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let n=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],r=i.slice(1),s=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...n,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.text}]}}),r.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let n=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),n)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return J(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,n){return this.emitter.on(e,n)}update(e){let n=this.opts.products,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==n||"showProducts"in e&&e.showProducts!==i)&&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)&&this.store.set({}),e.value!==void 0&&this.setValue(e.value),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let n=!this.store.get().text;this.applyOption(e),n&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let n=this.store.get();if(n.activeFormatType==="date-range"){let o=N(e);if(o){let r=n.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:be(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(vn(r,o));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(rn),this.reEdit.selectOption(e);return}let i=ti(n,e);if(i){if(this.fireTelemetry("option",{raw_query:R(n.text,n.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:w(n.activeFormatType)?[]:i.telemetry.otherOptions,key:i.telemetry.key,position:w(n.activeFormatType)?null:i.telemetry.position}),this.timers.clear(rn),this.store.set({...i.patch,...Ye(n)}),this.startSelectionAnimationTimer(),this.timers.clear(Yi),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(Yi,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},Qi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Gr,()=>this.store.set({inSelectionAnimation:!1}),Qi)}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(),n=e.suggestions.filter(r=>r.type!=="placeholder").map(r=>({key:r.type,options:(r.options??[]).slice(0,Wr).map(s=>s.text)})),i=e.products.map(r=>r.id);if(n.length===0&&i.length===0)return;let o=JSON.stringify([n,i]);o!==this.lastImpressionKey&&(this.lastImpressionKey=o,this.fireTelemetry("impression",{query:e.text,pills:n,product_ids:i}))}fireTelemetry(e,n){let i=this.funnelTelemetry===!0;if(!i&&qr.has(e))return;if(!i&&e==="option"){let{key:r,position:s,...a}=n;n=a}let o=this.resolveSource();ei({source:o,sessionId:this.sessionId,visitorId:i?this.resolveVisitorId():void 0,requestId:i?this.lastRequestId:null,keepalive:i,type:e,queryData:n,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),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 ve(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,n={store:this.store,listboxId:this.listboxId,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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o,!0),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Wi(this.container,n);let i=()=>{this.domRefs&&tn(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),tn(this.domRefs,this.store.get(),n),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,n={store:this.store,listboxId:this.listboxId,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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Ni(this.container,n);let i=()=>{this.dropdownRefs&&Zt(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Zt(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(Ve),i=()=>e();n.addEventListener("change",i),this.unsubscribers.push(()=>n.removeEventListener("change",i))}subscribeBatchedRender(e){let n=!1;this.unsubscribers.push(this.store.subscribe(()=>{n||(n=!0,queueMicrotask(()=>{n=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,n)=>{if(!e.skeletonOptions)return;if(!n.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!n.isLoading||e.isLoading)return;let i={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(i);return}this.timers.schedule(rn,()=>this.store.set(i),Yr)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule($r,()=>this.store.set({newParamId:null}),Ur)}))}handleChange(e,n){let i=this.store.get();n&&e&&!i.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:r}=Hn(e,i.completedParams);r.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=H(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Rn(e.segments,n);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(r=>r.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let n=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,n);j(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:i}=R(e.text,e.completedParams);this.fetchController.doFetch(n,i)}commitIdentifiedDate(e){let n=this.store.get(),i=n.editingIdentified;if(!i)return;if(n.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=n.text.slice(0,i.anchor),r=n.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=r.length===0||r[0]!==" "?`${s} `:s,d=o+l+r,c=d.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:K(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:R(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[],key:i.type,position:null}),this.store.set({text:d,completedParams:[...n.completedParams,u],identifiedParams:n.identifiedParams.filter(m=>m.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let n=this.store.get();if(w(n.activeFormatType))return;let i=Ke({mode:"fresh",text:e,completedParams:n.completedParams,suggestions:n.suggestions,filterBase:n.filterBase,filterInProgress:n.filterInProgress});i&&this.store.set(i.patch)}};export{sn as AIAutocomplete,ai as ATTRIBUTION_URL,gt as DATE_RANGE_META_END,ft as DATE_RANGE_META_START,wi as DEFAULT_OPTION_COUNT_UNIT,ve as ModeController,Ve as OPTIONS_GRID_MOBILE_QUERY,Kt as OPTION_ENTER_DELAY_VAR,rr as OPTION_ENTER_FADE_MS,sr as OPTION_ENTER_RISE_MS,ar as OPTION_ENTER_RISE_PX,or as OPTION_ENTER_STAGGER_MS,$o as PLACEHOLDER_FADE_OUT_MS,ae as PLACEHOLDER_LEAVING_ATTR,Go as PLACEHOLDER_SWAP_GAP_MS,Wo as PLACEHOLDER_TYPE_MS,qo as PLACEHOLDER_WORD_PAUSE_MS,Qn as PRODUCT_PATH_PREFIX,Zo as PRODUCT_ROW_PX_PER_LINE,Sn as RANGE_SEPARATOR,Li as SCROLL_ARROW_ATTR,Mi as SCROLL_ARROW_BOTTOM_VAR,Ai as SCROLL_ARROW_CLASS,Ri as SCROLL_ARROW_FADE_MS,ki as SCROLL_ARROW_LABEL,Di as SCROLL_ARROW_SCROLL_IDLE_MS,de as SCROLL_ARROW_VISIBLE_ATTR,Pn as SKIPPED_PARAM_TEXT,Ee as WEEKDAY_LABELS,lt as addMonths,$t as attachProductRowWheel,zt as attachScrollArrow,Nt as buildAttributionUrl,dt as buildDateOptions,R as buildQuery,J as buildSubmitResult,ut as cellDay,N as cellIso,Et as chipIdFromTap,jn as computeOptionsGridLayout,Ht as containScroll,nn as createStore,Pt as cursorIsAtEnd,Wt as dateCellMarks,ye as dateSelectionFor,We as extractPlainText,ne as formatAbsoluteDate,fn as formatDate,xn as formatDateRange,Se as formatOptionCount,_ as getCursorOffset,Ft as getFooterHint,K as identifiedParamLabel,w as isCalendarFormat,kt as isOptionsGridMobileViewport,k as isoDate,wt as keepCaretOnChip,Mt as measureOptionsGrid,st as monthLabel,Rt as needsOptionsGridMeasurement,lr as optionCountLabel,Yt as optionEnterDelayMs,dr as optionHasImage,U as optionImageSrc,Xt as optionLabel,Qt as optionsEntranceDurationMs,Lt as optionsGridTemplateColumns,we as parseDate,Y as parseLooseDate,ie as parseLooseDateRange,xt as plainTextLength,Dt as planOptionsGrid,Tt as previousGraphemeBoundary,Xn as productFromMatchedItem,Gt as productInitial,yi as productRowWheelTarget,Ot as productsFromCustomFields,en as renderEditableContent,Q as resolveFormatType,pt as resolveIdentifiedDate,_t as sameOptionRows,xe as sanitizeOptionIconSvg,bt as scrollCaretIntoView,ct as selectedIsoFromText,pe as selectedRangeFor,A as setCursorOffset,fe as toWireIdentifiedParams,Bt as visibleDateRange,ge as withSkippedParams};
2187
2243
  //# sourceMappingURL=index.mjs.map