@magicx-eng/ai-autocomplete-vanilla 0.28.2 → 0.30.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 et(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function $(n){let e=et(n);return e.length>0?e.join(" "):n}var J=["January","February","March","April","May","June","July","August","September","October","November","December"],Se=["S","M","T","W","T","F","S"],en=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],tn="aiaDate",nn="aiaDay",Jt=n=>String(n).padStart(2,"0");function k(n){return`${n.getFullYear()}-${Jt(n.getMonth()+1)}-${Jt(n.getDate())}`}function tt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Bo(n){let e=tt(n).getTime()-tt(new Date).getTime();return Math.round(e/864e5)}function on(n){let e=Bo(n);return e>=0&&e<7?en[n.getDay()]:Z(n)}function Z(n){return n.getFullYear()===new Date().getFullYear()?`${J[n.getMonth()]} ${n.getDate()}`:`${J[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function xe(n){if(!n)return null;let e=en.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=tt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let o=J.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(o<0)return null;let i=Number(t[2]),r=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(r,o,i);return s.getMonth()!==o||s.getDate()!==i?null:s}function nt(n){return`${J[n.month]} ${n.year}`}function ot(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function rn(n){return{year:n.getFullYear(),month:n.getMonth()}}function it(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Zt(){return{text:"",is_tappable:!1,kind:null}}function rt(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),o=[];for(let i=0;i<e;i++)o.push(Zt());for(let i=1;i<=t;i++){let r=new Date(n.year,n.month,i);o.push({text:on(r),is_tappable:!0,kind:null,metadata:{[tn]:k(r),[nn]:i}})}for(;o.length%Se.length!==0;)o.push(Zt());return o}function st(n){let e=xe(n);return e?k(e):null}function N(n){let e=n?.metadata?.[tn];return typeof e=="string"?e:null}function at(n){let e=n?.metadata?.[nn];return typeof e=="number"?e:null}function Wo(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function sn(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:J.findIndex(t=>t.toLowerCase().startsWith(e))}function Go(n,e,t){let o=new Date(t.getFullYear(),n,e);if(o.getMonth()!==n||o.getDate()!==e)return null;let i=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(o>=i)return o;let r=new Date(t.getFullYear()+1,n,e);return r.getMonth()===n&&r.getDate()===e?r:null}function an(n,e,t){let o=new Date(n,e,t);return o.getMonth()===e&&o.getDate()===t?o:null}function q(n,e={}){if(!n)return null;let t=e.today??new Date,o=Wo(n.trim().toLowerCase()).replace(/\s+/g," "),i=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(o);if(i){let l=an(Number(i[1]),Number(i[2])-1,Number(i[3]));return l?k(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(o);if(r){let l=sn(r[1]);if(l>=0)return ve(l,Number(r[2]),r[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(o);if(s){let l=sn(s[2]);if(l>=0)return ve(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(o);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?ve(c-1,l,a[3],t):c>12&&l<=12?ve(l-1,c,a[3],t):null}return null}function ve(n,e,t,o){if(t){if(t.length!==4)return null;let r=an(Number(t),n,e);return r?k(r):null}let i=Go(n,e,o);return i?k(i):null}function lt(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:q(n.text,e)}var dn=" - ",ct="aiaDateRangeStart",ut="aiaDateRangeEnd";function le(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var dt=/^\d{4}-\d{2}-\d{2}$/;function ln(n){if(!dt.test(n))return null;let[e,t,o]=n.split("-").map(Number),i=new Date(e,t-1,o);return i.getMonth()===t-1&&i.getDate()===o?i:null}var $o=/\s+(?:to|through|thru|until|til|till)\s+/g,qo=/[-–—]/g;function Uo(n){let e=[];for(let t of[$o,qo]){t.lastIndex=0;let o=t.exec(n);for(;o!==null;)e.push([n.slice(0,o.index),n.slice(o.index+o[0].length)]),o=t.exec(n)}return e}function ee(n,e={}){if(!n)return null;let t=new Set,o=null;for(let[i,r]of Uo(n.trim())){let s=q(i.trim(),e);if(!s)continue;let a=q(r.trim(),e);!a||a<s||(t.add(`${s}|${a}`),o={start:s,end:a})}return t.size===1?o:null}function cn(n){let e=ln(n.start),t=ln(n.end);return!e||!t?"":n.start===n.end?Z(e):`${Z(e)}${dn}${Z(t)}`}function un(n,e){let t=le(n,e);return{text:cn(t),is_tappable:!0,kind:null,metadata:{[ct]:t.start,[ut]:t.end}}}function de(n,e={}){let t=n?.metadata?.[ct],o=n?.metadata?.[ut];return typeof t=="string"&&typeof o=="string"&&dt.test(t)&&dt.test(o)?le(t,o):ee(n?.text,e)}function w(n){return n==="date"||n==="date-range"}var Vo=new Set(["date","dates"]),Ko=new Set(["range","ranges","span","period","window"]),pn=3;function Qo(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(ee(t.text)!==null?e.range+=1:q(t.text)!==null&&(e.single+=1));return e}function U(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Qo(n.options);if(t.single+t.range>=pn&&t.range>t.single)return"date-range";let o=et(n.type);return o.some(i=>Vo.has(i))?o.some(i=>Ko.has(i))?"date-range":"date":t.single>=pn?"date":"options"}var we=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 Yo="https://api.ai-autocomplete.com",Ee=`${Yo}/api/suggest`,mn=new WeakMap;function ce(n){return n?.type==="accessToken"}function jo(n){if(!(!n||ce(n)))return n}function Pe(n){let e=mn.get(n.getAccessToken);return e||(e=new we(n),mn.set(n.getAccessToken,e)),e}function Te(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ce(n){let e=jo(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ue(n){return n.map(e=>({type:e.type,value:e.text}))}var gn="skipped";function pe(n,e){if(e.length===0)return n;let t=new Set(n.map(i=>i.type)),o=e.filter(i=>!t.has(i.type)).map(i=>({placeholder:"",type:i.type,text:gn,kind:null}));return o.length>0?[...n,...o]:n}var zo="0.28.2",fn=!1;function Xo(){return crypto.randomUUID()}function Jo(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function Zo(n,e,t,o,i,r,s,a,l){let c=e.find(u=>u.type==="contact"&&u.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof c=="number"?c:void 0;return{data:{raw_query:n,completed_params:pe(e.map(u=>Jo(u,t)),a??[]),...r&&r.length>0&&{identified_params:ue(r)},...s&&s.length>0&&{recently_suggested:s},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:Xo(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:zo,session_id:o,source:i}}}async function hn(n,e,t,o,i){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:i})}async function bn(n,e,t){let o=t.apiConfig,i=!t.maskCompletedText,r=Zo(n,e,i,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Te(o),a=o?.endpoint??Ee,l=JSON.stringify(r);if(ce(o)){let u=Pe(o),m=await u.getToken(),g=await hn(a,s,m,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await hn(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=Ce(o);!c&&!fn&&(fn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(s.Authorization=c);let d=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function R(n,e){let t=n,o={},i=[],r=[],s=0;for(let a of e){let l=(o[a.type]??0)+1;o[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&r.some(S=>h<S.end&&h+a.text.length>S.start);)h=t.indexOf(a.text,h+1);return h},m=u(s);if(m===-1&&(m=u(0)),m!==-1){t=t.slice(0,m)+d+t.slice(m+a.text.length);let g=d.length-a.text.length;for(let h of r)h.start>=m+a.text.length&&(h.start+=g,h.end+=g);r.push({start:m,end:m+d.length}),s=m>=s?m+d.length:s+g}i.push({...a,placeholder:d})}return{rawQuery:t,completedParams:i}}function F(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Oe(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function V(n,e,t){let o=n.slice(e);if(t||e===0||n[e-1]===" ")return o;let i=o.indexOf(" ");return i===-1?"":o.slice(i+1)}function yn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),i=e.toLowerCase();for(let r=0;r<o.length;r++){let s=o.slice(r).join(" ");if(i.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function K(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let o=t.toLowerCase();return n.filter(i=>!i.is_tappable||i.text.toLowerCase().includes(o))}function te(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return n.find(i=>i.is_tappable&&i.text.toLowerCase()===o)??null}function Sn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function xn(n,e){let t=0,o=e;for(let i of n)t+=i.value.length,i.type!=="text"&&(o=Math.max(o,t));return o}function vn(n,e){let t=0;for(let o of n){let i=t+o.value.length;if(o.type==="text"&&i>e&&o.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=i}return!0}function wn(n,e){let t=[],o=new Set;for(let i of[...n,...e])i.type==="placeholder"||o.has(i.type)||(o.add(i.type),t.push({type:i.type,text:i.text}));return t}function En(n,e,t){if(n===e)return t;let o=Math.min(n.length,e.length),i=0;for(;i<o&&n[i]===e[i];)i++;if(i>=t)return t;let r=0;for(;r<o-i&&n[n.length-1-r]===e[e.length-1-r];)r++;return n.length-r<=t?t+(e.length-n.length):null}function pt(n,e){let t=[],o=[],i=0;for(let r of e){let s=n.indexOf(r.text,i);if(s===-1){o.push(r);continue}t.push({start:s,end:s+r.text.length,param:r}),i=s+r.text.length}return{located:t,missing:o}}function Pn(n,e,t){let o=[],i=[],r=0;for(let s of t){let a=n.indexOf(s.text,r);for(;a!==-1&&e.some(l=>a<l.end&&a+s.text.length>l.start);)a=n.indexOf(s.text,a+1);if(a===-1){i.push(s);continue}o.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:o,missing:i}}function Tn(n,e,t=[]){let o=pt(n,e).located,i=Pn(n,o,t).located,r=[...o.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...i.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),s=[],a=0;for(let c of r)c.start>a&&s.push({type:"text",value:n.slice(a,c.start)}),s.push(c.segment),a=c.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function Cn(n,e){let{located:t,missing:o}=pt(n,e);return{valid:t.map(i=>i.param),invalid:o}}function Ae(n,e,t){let o=pt(n,e).located,{located:i,missing:r}=Pn(n,o,t);return{valid:i.map(s=>s.param),invalid:r}}function ei(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var ti=100,ni=300,oi=2,Ie=class{constructor(e,t,o,i,r,s,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=i;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(o=>{(o.text!==e||o.completedParams!==t)&&(e=o.text,t=o.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let o=new AbortController;this.abortController=o;let i=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:o.signal,isCurrent:()=>i===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?wn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await bn(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(i!==this.fetchVersion)return;let c=(l.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),d=Sn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],m=u[u.length-1],g=this.store.get().text,h,S;if(m?.state==="in_progress"){S=!0;let x=g.toLowerCase().lastIndexOf(m.text.toLowerCase());h=x!==-1?x:r}else S=!1,h=r;let f=d.filter(x=>x.type!=="placeholder")[0],p=null;if(f&&!w(U(f))){let x=V(g,h,S),E=te(f.options,x);E&&(p={id:crypto.randomUUID(),placeholder:"",type:f.type,text:E.text,value:E.value,kind:E.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:E.metadata,icon:E.icon,icon_svg:E.icon_svg,image_url:E.image_url},d=d.filter(A=>A!==f),this.callbacks.onAutoMatch?.({active:f,matched:E,rawQuery:e}))}let b=l.data.custom_fields??null,y=this.callbacks.productsForResponse?.(b);this.store.set(x=>{let E=p?[...x.completedParams,p]:x.completedParams,A=Ae(x.text,E,c).valid,D=new Set(s.skippedParams.map(C=>C.id)),P=new Set(x.skippedParams.filter(C=>!D.has(C.id)).map(C=>C.type));return{suggestions:P.size>0?d.filter(C=>C.type==="placeholder"||!P.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:S,identifiedParams:A,customFields:b,...y!==void 0?{products:y}:{},...p?{completedParams:E}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=ei(s);i===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(i===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}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(oi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ti),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),ni)}attemptFetch(e,t=!1){let o=this.store.get();if(!o.text&&o.completedParams.length===0)return this.doFetch("",[]),!0;let i=this.callbacks.consumerTick?.(o,e)??"no";if(i==="asked")return!0;if(i==="owns")return!1;let r=o.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=F(o.text,o.filterBase,r),a=V(o.text,s,o.filterInProgress),c=o.suggestions.filter(y=>y.type!=="placeholder")[0],d=w(o.activeFormatType),m=(c&&!d?K(c.options,a):[]).filter(y=>y.is_tappable),g=c&&!d?te(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!g&&h||Oe(o.text,o.completedParams.length,r))return!1;let{rawQuery:S,completedParams:v}=R(o.text,o.completedParams),f=S.length<o.lastRawQuery.length,p=Math.abs(S.length-o.lastRawQuery.length),b=t&&S!==o.lastRawQuery;return f||p>=e||b?(this.doFetch(S,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function ii(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function Q(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&ii(e)?e:n.ownerDocument??n}function O(n){return n.ownerDocument??n}function ri(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function On(n){let e=Q(n);return!ri(e)||typeof e.getSelection=="function"?null:e}function An(n){let e=On(n);if(!e)return null;let t=O(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function In(n,e){let t=n,o;try{o=t.getComposedRanges({shadowRoots:[e]})}catch{o=t.getComposedRanges(e)}return o.length>0?o[0]:null}function mt(n){let t=Q(n).getSelection?.();return t||(O(n).getSelection?.()??null)}function Y(n){let e=mt(n);if(!e||e.rangeCount===0)return null;let t=An(n);if(t){let o=In(e,t);return o?{node:o.startContainer,offset:o.startOffset,collapsed:o.startContainer===o.endContainer&&o.startOffset===o.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Re(n){let e=mt(n);if(!e||e.rangeCount===0)return null;let t=An(n);if(!t)return e.getRangeAt(0);let o=In(e,t);if(!o)return null;let i=O(n).createRange();return i.setStart(o.startContainer,o.startOffset),i.setEnd(o.endContainer,o.endOffset),i}function me(n,e,t){let o=mt(n);if(!o)return null;if(On(n))return o.collapse(e,t),o;let i=O(n).createRange();return i.setStart(e,t),i.collapse(!0),o.removeAllRanges(),o.addRange(i),o}function Le(n,e){let t=n?Q(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var De=2,si="magicx-aia";function Rn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function ai(n){let e=O(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let o=n;for(;o&&o!==e.body&&o!==e.documentElement;){let i=o.scrollWidth>o.clientWidth,r=o.scrollHeight>o.clientHeight;if(i||r){let s=t.getComputedStyle(o);if(i&&Rn(s.overflowX)||r&&Rn(s.overflowY))return o}if(o.classList.contains(si))return null;o=o.parentElement}return null}function gt(n){let e=Re(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=ai(n);if(!t||typeof e.getBoundingClientRect!="function")return;let o=e.getBoundingClientRect();if(o.height===0)return;let i=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let r=i.left+t.clientLeft,s=r+t.clientWidth;o.right>s?t.scrollLeft+=o.right-s+De:o.left<r&&(t.scrollLeft-=r-o.left+De)}if(t.scrollHeight>t.clientHeight){let r=i.top+t.clientTop,s=r+t.clientHeight;o.bottom>s?t.scrollTop+=o.bottom-s+De:o.top<r&&(t.scrollTop-=r-o.top+De)}}var Mn='[contenteditable="false"]',li="strong[data-param-id]",ne;function di(){if(ne!==void 0)return ne;let n=globalThis.Intl.Segmenter;if(!n)return ne=null,null;try{ne=new n(void 0,{granularity:"grapheme"})}catch{ne=null}return ne??null}function Me(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Mn))return!0;t=t.parentNode}return!1}function ke(n){return O(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Me(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function _e(n){let e=ke(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function ft(n){let e=ke(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function _(n){let e=Y(n);if(!e)return null;let t=e.node,o=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let i=t;if(Me(i,n)&&i!==n)return null;let r=0;for(let s=0;s<o&&s<i.childNodes.length;s++)r+=kn(i.childNodes[s],n);return r+Ln(i,n)}return t.nodeType!==Node.TEXT_NODE||Me(t,n)?null:Ln(t,n)+o}function kn(n,e){if(n.nodeType===Node.TEXT_NODE)return Me(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Mn))return 0;let o=0;for(let i of Array.from(t.childNodes))o+=kn(i,e);return o}function Ln(n,e){let t=ke(e),o=0,i=t.nextNode();for(;i;){if(i===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(i))return o;o+=i.data.length,i=t.nextNode()}return o}function L(n,e){let t=O(n),o=Math.max(0,Math.min(e,ft(n))),i=ke(n),r=0,s=null,a=0,l=i.nextNode(),c=null;for(;l;){let u=l.data.length;if(o<r+u){s=l,a=o-r;break}if(o===r+u){let m=i.nextNode();m?(s=m,a=0):(s=l,a=u);break}r+=u,c=l,l=i.nextNode()}let d=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===s.data.length?d.setStartAfter(u):d.setStart(s,a):d.setStart(s,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),me(n,d.startContainer,d.startOffset)&&(ci(n,d,o),gt(n))}function Dn(n,e){if(!n||!e.contains(n))return null;let o=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(li)??null;return o&&e.contains(o)?o:null}function ci(n,e,t){let o=Dn(Y(n)?.node??null,n);if(o&&o!==Dn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${o.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function _n(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let o=_(n);return o!==null&&t===`${o}:${e}`}function Nn(n){return Q(n).activeElement===n}function ht(n){let e=_(n);return e==null?!1:e>=ft(n)}function bt(n,e){if(e<=0)return 0;let t=di();if(!t)return e-1;let o=n.slice(0,e),i=0;for(let{index:r}of t.segment(o))r<e&&(i=r);return i}function j(n,e,t=[],o={}){let{rawQuery:i,completedParams:r}=R(n,e);return{query:n.trim(),raw_query:i,completed_params:pe(r,t),identified_params:ue(o.identifiedParams??[]),is_ready:o.isReady??!1,...o.customFields?{custom_fields:o.customFields}:{}}}function yt(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?ht(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function St(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?_(n):null}var Ne=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:i}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=i(),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 c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=yt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=w(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.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(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(t.activeDropdownIndex),g=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let m=yt(e.target,t),g=!!t.editingParam;if(!m&&!g)break;e.preventDefault();let h=w(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.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(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),L(u,m);break}yt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=St(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),L(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=St(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=St(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o,r):a&&a(j(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),m;if(u<0)m=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;m=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[m]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),L(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let i=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=i;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,t){let o=k(new Date),i=e.filteredOptions.findIndex(s=>N(s)===o);if(i>=0)return i;let r=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?r[r.length-1]:r[0])??0}stepDateDay(e,t){for(let o=e.activeDropdownIndex+t;o>=0&&o<e.filteredOptions.length;o+=t)if(e.filteredOptions[o]?.is_tappable){this.store.set({activeDropdownIndex:o});return}}stepDateWeek(e,t){let o=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[o]?.is_tappable?o:-1})}getTappableIndices(e){let o=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),i=Array.from({length:e},()=>[]);for(let r of o)i[r%e].push(r);return i.flat()}getEffectiveColumns(e){let t=Le(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let i=Le(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(i===t)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,o,i){let r=Le(i,`${o}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var Fe=class{constructor(e,t,o={}){this.store=e;this.getOverrides=t;this.callbacks=o;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let o=this.resolveTarget(e);if(!o||this.missCovers(o.type,o.query))return"no";let i=this.current;if(i&&i.key===o.key){if(i.query===o.query)return"owns";let r=Math.abs(o.query.length-i.query.length),s=o.query.length<i.query.length;if(t>1&&!s&&r<t)return"owns"}return this.ask(o),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(w(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let o=e.actionableSuggestions[0];return!o||!this.hasOverride(o.type)?null:{mode:"pill",key:o,type:o.type,suggestion:o,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],o=++this.version;if(!t||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 i=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:i};let r;try{r=t(e.query,i.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],o);return}if(Array.isArray(r)){this.commit(e,r,o);return}this.setSearch(e,"loading"),this.await(e,r,i.signal,o)}async await(e,t,o,i){let r;try{let s=await t;if(o.aborted||i!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(o.aborted||i!==this.version||ui(s))return;this.logOnce(s),r=[]}this.commit(e,r,i)}commit(e,t,o){if(o!==this.version)return;let i=this.resolveTarget(this.store.get());if(!i||i.key!==e.key)return;t.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:t}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:t};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}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let o=this.store.get().optionSearch;o&&o.type===e.type&&o.query===e.query&&o.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function ui(n){return n instanceof Error&&n.name==="AbortError"}var He=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),o=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=o.length)return;let i=o[e],r=o.filter((c,d)=>d!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=R(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:i.text,otherPills:r.map(d=>d.text)})}let a=[...s,i,...r],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Hn="/products/",Fn="https://relative.invalid";function pi(n){if(!n)return;let e;try{e=new URL(n,`${Fn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Fn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Bn(n){let e=pi(n.item_url)??(n.handle?`${Hn}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function xt(n){return(n?.items.matched??[]).map(Bn)}var Be=class{constructor(e,t,o=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=o;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return xt(e)}async run(e,t,o){if(!this.isEnabled())return;let i=this.getConfig();if(!i)return;if(e.trim().length===0){this.clear(o);return}let r=()=>t.aborted||!o()||!this.owns(i);try{let s=await i.fetch(e,t);if(r())return;let a=i.transform(s),l=Array.isArray(a)?a:[],c=i.limit!=null?l.slice(0,i.limit):l;if(r())return;this.commit(c)}catch(s){if(t.aborted||mi(s)||(this.logOnce(s),r()))return;this.clear(o)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function mi(n){return n instanceof Error&&n.name==="AbortError"}var We="(max-width: 768px)";var gi="var(--aia-option-row-height, 37px)",fi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function Wn(n,e){return e?vt(1,Math.min(n,5)):vt(1,Math.min(n,4))}function vt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${gi} + ${fi})`}}function Et(n,e){return!e&&n>=5}function Pt(n,e,t,o){if(!(!e&&n>=5&&hi(t,o))){let s=Wn(n,e);return{...s,template:wt(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let r=6;return{...vt(2,3),template:wt(2),scrollHintIndices:n>r?[r-2,r-1]:[]}}function hi(n,e){return!n||n.length===0||e==null||e<=0||n.some(o=>o<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function Tt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let 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",t.appendChild(a)}n.appendChild(t);let o=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let i=getComputedStyle(n),r=n.clientWidth-(Number.parseFloat(i.paddingLeft)||0)-(Number.parseFloat(i.paddingRight)||0)-(Number.parseFloat(i.columnGap)||0);return{rowWidths:o,gridWidth:r}}function wt(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Ct(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(We).matches}function Ot(n,e){return!n||n.length!==e.length?!1:n.every((t,o)=>t.text===e[o].text)}function Gn(n,e){let t=e.dropdownTrigger??"auto",o=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=o?n.isFocused:!0;return s&&a}if(t==="auto"){let a=o?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&c}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function ge(n){if(n.editingIdentified){let{type:t,anchor:o}=n.editingIdentified;return`identified:${t}@${o}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function $n(n){if(!n)return ot();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function bi(n){let e=xe(n);return e?rn(e):ot()}function qn(n,e){let t=Tn(n.text,n.completedParams,n.identifiedParams),o=n.suggestions.filter(T=>T.type!=="placeholder"),i=o[0],r=n.suggestions.filter(T=>T.type==="placeholder").map(T=>T.text).join(" "),s=F(n.text,Math.min(n.filterBase,n.text.length),r),l=s===0&&Oe(n.text,n.completedParams.length,r)?"":V(n.text,s,n.filterInProgress),c=i?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,m,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let T=n.editingParam.id,X=n.completedParams.some(Ho=>Ho.id===T),ae=n.caretOffset??n.editingAnchor,Xt=X?"":n.text.slice(n.editingAnchor,ae);m=Xt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=K(n.editingParam.options,Xt)}else m=l.trim(),g=c,h=i?.type,u=K(c,l);let S=n.optionSearch,v=S!=null&&h!=null&&S.type===h;v&&S.status==="done"&&S.query===m&&(u=g);let f=v&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(T=>T.is_tappable));let b=n.editingIdentified,y=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:i,x=b?b.format:U(y),E=d&&w(x)?de(n.editingParam):null;E&&(x="date-range");let A=null,D=null;if(w(x)){let T=ge({...n,actionableSuggestions:o}),X=n.dateViewMonth;A=X&&X.key===T?{year:X.year,month:X.month}:b?$n(b.iso):E?$n(E.start):bi(n.editingParam?.text),u=rt(A);let ae=n.pendingRangeStart;x==="date-range"&&ae&&ae.key===T&&(D=ae.iso)}let P=T=>p?T.is_tappable:!0,I;if(d){let T=n.editingParam?.options??[];I=n.editingParam!=null&&T.filter(P).length===0}else I=i!=null&&c.filter(P).length===0;let C=Gn({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||f,pillTapped:n.pillTapped,activePillHasNoOptions:I,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Ze=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable,M=n.skeletonOptions!==null&&n.skeletonRequested&&!n.isLoading&&!n.editingParam&&!n.inSelectionAnimation,z=n.isLoading&&!n.editingParam&&!n.inSelectionAnimation||f||M,zt=z&&n.skeletonOptions!==null,No=zt&&n.skeletonOptions?n.skeletonOptions:u,Fo=zt?n.skeletonSuggestion:null;return{segments:t,actionableSuggestions:o,filteredOptions:u,dropdownLoading:z,dropdownOptions:No,dropdownSuggestion:Fo,skeletonExiting:M,activeFormatType:x,dateView:A,dateRangeStart:D,placeholderText:r,optionQuery:m,isSearchingOptions:f,isDropdownOpen:C,isActivePillSelected:Ze}}function Ge(n){return n.mode==="fresh"?yi(n):Si(n)}function yi(n){let{text:e,completedParams:t,suggestions:o,filterBase:i,filterInProgress:r}=n,a=o.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=o.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),c=F(e,i,l),d=V(e,c,r),u=te(a.options,d);if(!u)return null;let m=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(m),h=g>=0?g:Math.max(0,e.length-u.text.length),S=h+u.text.length,v=e.slice(h,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,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:[...t,b],suggestions:o.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function Si(n){let{text:e,completedParams:t,editingParam:o,editingAnchor:i,editingTail:r}=n;if(t.some(b=>b.id===o.id))return null;let s=e.slice(i,r),a=te(o.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=i+Math.max(0,c),u=d+a.text.length,m=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,S={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:m,value:a.value,kind:a.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},v=t.length,f=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,f);if(y!==-1){if(y>=g){v=b;break}f=y+t[b].text.length}}let p=[...t];return p.splice(v,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Un(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let o=n.filterBase,i=n.text.slice(0,o),r=i.length===0&&n.text.length===0,s=i.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(i=`${n.placeholderText} `);let a=yn(i,e.text);a>0&&(i=i.slice(0,i.length-a));let l=i.length>0&&i[i.length-1]!==" ",c=`${i}${l?" ":""}${e.text} `,d=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,value:e.value,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(S=>S.text!==e.text).map(S=>S.text)},consumedSuggestion:t,remainingActionable:h}}function $e(n){let e=w(n.activeFormatType)||n.filteredOptions.length===0?null:n.filteredOptions,t=n.editingParam,o=t?{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options}:n.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?o:null,skeletonRequested:!1}}function qe(n,e,t){let o=n.slice(0,e),i=n.slice(t),r=(o===""||o.endsWith(" "))&&i.startsWith(" ");return r&&(i=i.slice(1)),{text:o+i,removed:t-e+(r?1:0)}}var Ue=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let o=t.completedParams.find(s=>s.id===e);if(!o)return;let i=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,i);if(a!==-1){if(s.id===e){r=a;break}i=a+s.text.length}}r<0||this.deps.store.set({editingParam:o,editingAnchor:r,editingTail:r+o.text.length,caretOffset:r+o.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),o=t.editingParam,i=t.editingAnchor,r=t.editingTail;if(!o||i==null||r==null||!t.completedParams.some(l=>l.id===o.id))return!1;let{text:s}=e===""?qe(t.text,i,r):{text:t.text.slice(0,i)+e+t.text.slice(r)},a=i+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==o.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),o={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(o.editingParam=null,o.editingAnchor=null,o.editingTail=null,o.activeDropdownIndex=-1):t.editingTail!=null&&(o.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(o),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),o=t.editingParam,i=t.editingAnchor,r=t.editingTail;if(!o||i==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:o.options.filter(f=>f.text!==e.text).map(f=>f.text)});let s=t.text.slice(0,i),a=t.text.slice(r),l=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,m=u.length,g={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=t.completedParams.findIndex(f=>f.id===o.id),S=t.completedParams.filter(f=>f.id!==o.id),v=h>=0?Math.min(h,S.length):S.length;S.splice(v,0,g),this.deps.store.set({text:u,completedParams:S,newParamId:g.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...$e(t)}),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 t=Ge({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var xi=33,vi=70,wi=120,Ei=50,oe="data-aia-placeholder-leaving",ie=new WeakMap;function Ve(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Pi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Kn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Qn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Kn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],o=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Qn(n,e),33+o)}function Vn(n,e){Kn(n,e,0),e.timer=setTimeout(()=>Qn(n,e),33)}function Yn(n,e){let t=ie.get(n);if(e===""){t&&(Ve(t),ie.delete(n)),n.removeAttribute(oe),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Pi(n)){t&&Ve(t),n.removeAttribute(oe),ie.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let o={target:e,shown:0,timer:null},i=t&&t.shown>0?t:null;if(t&&Ve(t),ie.set(n,o),i){n.setAttribute(oe,""),o.timer=setTimeout(()=>{o.timer=null,n.removeAttribute(oe),n.isConnected&&Vn(n,o)},170);return}n.removeAttribute(oe),Vn(n,o)}function jn(n){let e=ie.get(n);e&&(Ve(e),ie.delete(n))}var zn="https://ai-autocomplete.com";function At(n=zn){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function It(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Xn=new WeakMap,Jn=new WeakSet;function H(n,e,t){if(Xn.set(n,t),Jn.has(n))return;Jn.add(n);let o=()=>Xn.get(n),i=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&n.contains(s)?s:null};e.onClick&&n.addEventListener("click",r=>{let s=i(r.target);s&&e.onClick?.(s,o(),r)}),e.onEnter&&n.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,o())},!0),e.preventMousedown&&n.addEventListener("mousedown",r=>r.preventDefault())}function re(n){return Number.parseInt(n.dataset.aiaIndex??"-1",10)}function B(n){n.offsetWidth}var Ti={selectedIso:null,selectedRange:null,rangeStart:null};function fe(n){if(!w(n.activeFormatType))return Ti;let e=n.editingIdentified;if(e){let{iso:o,isoEnd:i}=e;return{selectedIso:i?null:o,selectedRange:o&&i?le(o,i):null,rangeStart:n.dateRangeStart}}let t=de(n.editingParam);return{selectedIso:t?null:st(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function Rt(n){return n.pendingStart?le(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Lt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:o}=e,i=n===t||o!=null&&(n===o.start||n===o.end),r=o!=null&&n>o.start&&n<o.end;return{selected:i,inRange:r}}var Zn="data-aia-key";function W(n,e,t){let o=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Zn);a!=null&&o.set(a,s)}let i=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);i.add(l);let c=o.get(l);c||(c=t.create(a,s),c.setAttribute(Zn,l)),t.update?.(c,a,s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null),r.push(c)}for(let[s,a]of o)i.has(s)||a.remove();return r}function eo(n,e){if(!e.interactive)return null;let t=e.options[re(n)];return t?.is_tappable?t:null}var Ci={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(n,e)=>{if(n.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(n.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let t=eo(n,e);t&&(n.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(n,e)=>{n.hasAttribute("data-aia-date-cell")&&eo(n,e)&&e.callbacks.onHighlight(re(n))}};function no(n,e,t,o,i,r,s,a=!0){let l=n.querySelector(".magicx-aia-datepicker");if(!i||e.length===0){l?.remove();return}if(!l){l=Ii(),n.appendChild(l),B(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}H(l,Ci,{options:e,callbacks:s,interactive:a});let c=l.querySelector(".magicx-aia-datepicker-month");c&&(c.textContent=nt(i));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&Oi(d,e,t,o,r)}function Oi(n,e,t,o,i){let r=k(new Date),s=Rt({pendingStart:i.rangeStart,highlightedIso:N(e[t]),selected:i.selectedRange});W(n,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>Ai(a),update:(a,l,c)=>{let d=N(l),u=Lt(d,{selectedIso:i.selectedIso,range:s}),m=c===t&&l.is_tappable;a.id=`${o}-option-${c}`,a.dataset.aiaIndex=String(c),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",d!=null&&d<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",d!=null&&d===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function Ai(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=at(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let o=document.createElement("span");return o.className="magicx-aia-date-cell-number",o.textContent=String(t),e.appendChild(o),e}function Ii(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(to("prev","Previous month","\u2039"),t,to("next","Next month","\u203A"));let o=document.createElement("div");o.className="magicx-aia-datepicker-weekdays",o.setAttribute("aria-hidden","true");for(let r of Se){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,o.appendChild(s)}let i=document.createElement("div");return i.className="magicx-aia-datepicker-grid",i.setAttribute("data-aia-date-grid",""),n.append(e,o,i),n}function to(n,e,t){let o=document.createElement("button");return o.type="button",o.tabIndex=-1,o.className="magicx-aia-datepicker-nav",o.setAttribute(`data-aia-date-${n}`,""),o.setAttribute("aria-label",e),o.textContent=t,o.disabled=!0,o}var Ri={itemSelector:"[data-aia-pill]",onClick:(n,e)=>{if(e.loading||n.disabled)return;let t=Number.parseInt(n.dataset.aiaPillIndex??"-1",10);t>=0&&e.onSelectPill(t)},preventMousedown:!0},oo=[125,69];function io(n,e){return e?1:n===0?.7:n===1?.4:.2}function Ke(n,e,t,o,i=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),H(a,Ri,{onSelectPill:o,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<oo.length;l++){let c=oo[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${i?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(io(l,!1)),a.appendChild(d)}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();W(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.disabled=!0,c},update:(l,c,d)=>{let u=l,m=s&&d===t&&!r,g=["magicx-aia-pill"];i&&g.push("magicx-aia-pill--rounded"),r&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(io(d,m)),u.dataset.aiaPillIndex=String(d),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),B(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function Dt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Li=32;function ro(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,o=e.deltaX||0;if(!t||Math.abs(o)>=Math.abs(t))return null;let i=n.scrollWidth-n.clientWidth;if(i<=1)return null;let r=n.scrollLeft,s=t;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=n.clientWidth),Math.max(0,Math.min(i,r+s))}function Mt(n){let e=t=>{let o=ro(n,t);o!==null&&(t.preventDefault(),n.scrollLeft=o)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var kt=new WeakMap,Di="Products";function so(n,e,t,o,i,r="row"){let s=n.querySelector(".magicx-aia-products");if(e.length===0){s?.remove();return}if(!s){s=document.createElement("section"),s.className="magicx-aia-products",s.setAttribute("data-aia-products",""),s.setAttribute("role","group"),s.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=Di;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),Mt(c),s.append(l,c),n.appendChild(s)}s.setAttribute("data-aia-products-layout",r);let a=s.querySelector(".magicx-aia-products-row");if(a){W(a,e,{keyOf:l=>Mi(l),create:l=>ki(l,o,i),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}}),B(a);for(let l of a.querySelectorAll("[data-aia-product]")){let c=kt.get(l);c&&(kt.delete(l),c())}}}function _t(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let o of t)o.tabIndex=e?0:-1}function Mi(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function ki(n,e,t){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 i=document.createElement("span");if(i.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",i.appendChild(a)}else i.setAttribute("data-aia-product-placeholder","");o.appendChild(i);let r=document.createElement("span");if(r.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,r.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,r.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,r.appendChild(a)}return o.appendChild(r),kt.set(o,()=>{n.url&&(o.href=n.url),o.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))})}),o.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),o.addEventListener("focus",()=>t(!0)),o.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),o}var _i=80,Ni=150,Fi=280,Hi=16,Nt="--aia-option-enter-delay";function Ft(n,e,t,o="below"){let i=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,n)/i);if(o!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/i));return Math.max(0,s-1-r)*80}function Ht(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}function G(n){if(!n)return null;let e=n.trim();if(e==="")return null;let t;try{t=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.href}function he(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var ao={one:"item",other:"items"};function Bi(n,e=ao){let t=he(n);if(t===null)return null;let o=typeof e=="string"?e:n===1?e.one:e.other;return o===""?t:`${t} ${o}`}function Wi(n){return G(n.image_url)!==null}var lo="http://www.w3.org/2000/svg",Gi=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function $i(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var qi=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],Ui=/^[a-zA-Z0-9#.,%\s()-]+$/;function Vi(n){let e=[];for(let t of qi){let o=n.getAttribute(t);o===null||!Ui.test(o)||/url\s*\(/i.test(o)||e.push(`${t}: ${o.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function co(n){for(let e of Array.from(n.attributes))$i(e.name,e.value)&&n.removeAttribute(e.name);Vi(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Gi.has(t.localName)||t.namespaceURI!==lo?t.remove():co(t)}else e.remove()}function be(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==lo||e.getElementsByTagName("parsererror").length>0?null:(co(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function Bt(n){return n.text}var uo=new WeakMap;function Ki(n,e,t){let o=e.length,i=Ct(),r=uo.get(n),s=t&&r&&Ot(r.options,e)?r.plan:null,a=!s&&!t&&Et(o,i)?Tt(n):null,l=s??Pt(o,i,a?.rowWidths??null,a?.gridWidth??null);return t||uo.set(n,{options:e,plan:l}),n.style.gridTemplateColumns=l.template,n.style.setProperty("--aia-grid-max-height",l.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((c,d)=>{c.classList.toggle("magicx-aia-option--scroll-hint",!t&&l.scrollHintIndices.includes(d))}),l.cols}function po(n,e){if(e.loading||!e.interactive)return null;let t=e.options[re(n)];return t?.is_tappable?t:null}var Qi={itemSelector:"[data-aia-option]",onClick:(n,e)=>{let t=po(n,e);t&&(n.classList.add("magicx-aia-option--pressed"),e.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(n,e)=>{po(n,e)&&e.onHighlight(re(n))}};function mo(n,e,t,o,i,r,s,a="",l="below",c=!0,d=!0,u=!0,m=!0){let g=n.querySelector(".aia-grid");if(e.length===0){g?.remove();return}g||(g=document.createElement("div"),g.className="aia-grid magicx-aia-grid",g.setAttribute("data-scroll",""),g.style.setProperty("--aia-grid-min","250px"),g.style.setProperty("--aia-grid-max","1fr"),g.style.setProperty("--aia-grid-gap","0"),n.appendChild(g)),H(g,Qi,{options:e,onSelect:o,onHighlight:i,loading:s,interactive:m});let h=g.dataset.aiaGroup!==a;g.dataset.aiaGroup=a,Yi(g,e,t,r,s,{showIcons:c,showImages:d,showCounts:u});let S=Ki(g,e,s);ji(g,e.length,S,s,l),h&&(g.scrollTop=0)}function Yi(n,e,t,o,i,r){let s=i?"1":"0",a=n.dataset.aiaGroup??"",{showIcons:l,showImages:c,showCounts:d}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=c?h=>G(h.image_url)??"":()=>"",g=d?h=>he(h.item_count)??"":()=>"";W(n,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${g(h)}\0${s}\0${a}`,create:(h,S)=>{let v=zi(h,i,r);return i||(v.dataset.aiaEntering=""),v},update:(h,S,v)=>{let f=v===t&&!i;h.id=`${o}-option-${v}`,h.dataset.aiaIndex=String(v),h.setAttribute("aria-selected",String(f)),h.classList.toggle("magicx-aia-option--highlighted",f)}})}function ji(n,e,t,o,i){for(let r of n.querySelectorAll("[data-aia-entering]")){if(!o){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Nt,`${Ft(s,t,e,i)}ms`)}delete r.dataset.aiaEntering}}function zi(n,e,{showIcons:t,showImages:o,showCounts:i}){let r=document.createElement("div");r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),e&&r.setAttribute("data-aia-loading",""),r.tabIndex=e||!n.is_tappable?-1:0;let s=["magicx-aia-option"];n.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=o?G(n.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.setAttribute("aria-hidden","true");let g=document.createElement("img");g.setAttribute("alt",""),g.setAttribute("loading","lazy"),g.setAttribute("decoding","async"),g.setAttribute("referrerpolicy","no-referrer"),g.setAttribute("draggable","false"),g.onerror=()=>{g.hidden=!0},g.src=l,m.appendChild(g),a.appendChild(m),r.dataset.aiaImage=""}let c=!l&&t&&n.icon_svg?be(n.icon_svg):null;if(c){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=c,a.appendChild(m),n.icon&&(r.dataset.aiaIcon=n.icon)}let d=document.createElement("span");if(d.className="magicx-aia-option-text",d.textContent=Bt(n),a.appendChild(d),n.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=n.tag,a.appendChild(m)}let u=i?he(n.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(n.item_count)}return r.appendChild(a),r}var go="magicx-aia-scroll-arrow",fo="data-aia-scroll-arrow",se="data-aia-visible",ho=1e3,bo=160,yo="--aia-scroll-arrow-bottom",So="Scroll down for more options",Xi="[data-aia-products-label]",Ji=4,Zi=8,er=240;function tr(n,e,t,o){let i=n.scrollTop,r=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!r||s||Wt(n)){n.scrollTop=i+e,o();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/er),u=1-(1-d)*(1-d);n.scrollTop=i+e*u,d<1?r.call(t,c):o()};r.call(t,c)}function nr(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let o=n.createElementNS(e,"path");return o.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(o),t}function xo(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=go,e.setAttribute(fo,""),e.setAttribute("aria-label",So),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(nr(n)),e}function or(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Wt(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Gt({dropdown:n,grid:e,button:t}){let o=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),i=!1;t.disabled=!0;let r=null,s=null,a=null,l=null,c=p=>{if(p){if(t.hasAttribute(se))return;if(t.setAttribute(se,""),t.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),Wt(e)){t.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&t.hasAttribute(se)&&(t.disabled=!1)},ho)}else t.removeAttribute(se),t.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,t.disabled=!0},d=p=>{let b=0,y=p;for(;y&&y!==n;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=n.querySelector(Xi),b;if(p){let y=d(p)+p.offsetHeight/2;b=n.clientHeight-y-t.offsetHeight/2}else{let y=d(e),x=o&&Number.parseFloat(o.getComputedStyle(e).paddingBottom)||0;b=n.clientHeight-(y+e.offsetHeight)+(x>0?0:Zi)}t.style.setProperty(yo,`${Math.max(0,Math.round(b))}px`)},m=()=>{if(i||s!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,b=e.scrollHeight-e.clientHeight-e.scrollTop;c(!p&&b>Ji)},g=()=>{if(i)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,c(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=Wt(e)?0:Ht(b,or(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{i||s!==null||(c(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},bo))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),v=()=>{let p=o?(Number.parseFloat(o.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(o.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-p);tr(e,b,o,h)};t.addEventListener("mousedown",S),t.addEventListener("click",v);let f=null;return o&&typeof o.ResizeObserver=="function"&&(f=new o.ResizeObserver(()=>{u(),m()}),f.observe(e)),g(),{update:g,destroy(){i||(i=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,t.disabled=!0,e.removeEventListener("scroll",h),t.removeEventListener("mousedown",S),t.removeEventListener("click",v),f?.disconnect(),t.removeAttribute(se),t.setAttribute("aria-hidden","true"))}}}var ir=[159,119,164];function Ye(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}var Qe=new WeakMap;function rr(n,e){let t=Qe.get(n);if(t||(t={button:xo(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Qe.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Gt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function $t(n){let e=Qe.get(n);e&&(e.controller?.destroy(),Qe.delete(n))}function je(n,e){let{filteredOptions:t,activeIndex:o,isOpen:i,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:m}=e,g=s.length>0,h=a&&g,S=t.length>0,v=e.products.length>0,f=i&&(S||h||r||v);if(f?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),r?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!f){_t(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products"),n.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let p=n.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),n.appendChild(p));let b=e.showSkipButton&&g&&!e.isInputEmpty,y=h||r&&a||b,x=p.querySelector(".magicx-aia-pill-bar");if(y){x||(x=document.createElement("div"),x.className="magicx-aia-pill-bar aia-cluster",x.setAttribute("data-nowrap",""),x.setAttribute("data-aia-pillbar",""),p.insertBefore(x,p.firstChild));let M=x.querySelector(".magicx-aia-pill-scroll");M||(M=document.createElement("span"),M.className="magicx-aia-pill-scroll",M.setAttribute("data-aia-pill-scroll",""),x.insertBefore(M,x.firstChild)),Ke(M,a?s:[],0,u,!0,r&&a,l),lr(x,b,r||e.skipDisabled,s[0],m)}else x&&x.remove();let E=e.suggestions[0],A=E?`${E.type} ${E.text}`:"",D=w(e.formatType),P=D&&!r;mo(p,D?[]:t,o,c,d,e.listboxId,r,A,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),rr(n,p.querySelector(".aia-grid")),no(p,P?t:[],o,e.listboxId,P?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let I=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||D)){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();so(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),_t(n,!0);let C=p.querySelector(".magicx-aia-footer")??cr(),Ze=o>=0&&!!t[o]?.is_tappable;dr(C,It(Ze,e.isInputEmpty)),C.isConnected||p.appendChild(C),sr(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function sr(n,e){let t=e.map(o=>n.querySelector(`:scope > ${o}`)).filter(o=>o!==null);for(let o=0;o<t.length;o++)n.children[o]!==t[o]&&n.insertBefore(t[o],n.children[o]??null)}var ar={itemSelector:".magicx-aia-skip",onClick:(n,e)=>{e.loading||e.onSkip()}};function lr(n,e,t,o,i){H(n,ar,{onSkip:i,loading:t});let r=n.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,n.appendChild(r),B(r)),r.setAttribute("aria-label",o?`Skip ${o.text}`:"Skip"),r.disabled=t}function dr(n,{key:e,hint:t}){let o=n.querySelector(".magicx-aia-footer-key"),i=n.querySelector(".magicx-aia-footer-hint");!o||!i||(o.textContent!==e&&(o.textContent=e),i.textContent!==t&&(i.textContent=t))}function cr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.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 t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let o=document.createElement("kbd");o.className="magicx-aia-footer-key",o.textContent="tab";let i=document.createElement("span");i.className="magicx-aia-footer-hint",i.textContent="to select",t.append(o,i);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=At(),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(t,r),n.append(e),n}function vo(n,e){let t=Ye(e.listboxId);return n.appendChild(t),{dropdown:t}}function qt(n,e,t){let o=fe(e);je(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:$(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:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:o.selectedIso,selectedDateRange:o.selectedRange,dateRangeStart:o.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var ur=6,pr=.3;function wo(n){return n<=0?"0px":`${(-Math.min(pr,2*ur/n)).toFixed(3)}px`}function Ut(n){let{input:e,segments:t,newParamId:o,editingParamId:i,placeholderText:r,isFocused:s}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",Yn(e,c?r:"");let d=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?G(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",g=e.dataset.editingParamId??"";if(d===u&&(o??"")===m&&(i??"")===g)return;if(d===u){e.dataset.newParamId=o??"",e.dataset.editingParamId=i??"";for(let p of e.querySelectorAll("strong[data-param-id]")){let b=p.dataset.paramId,y=p.dataset.seg==="completed"&&b===o;p.classList.toggle("magicx-aia-shimmer-revealed",y),p.classList.toggle("magicx-aia-shimmer-sweep",y),p.classList.toggle("magicx-aia-segment--editing",b===i)}return}let h=s?_(e):null;e.dataset.segKey=d,e.dataset.newParamId=o??"",e.dataset.editingParamId=i??"";let S=O(e),v=S.createDocumentFragment(),f=0;for(let p of t)if(f+=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===o,x=p.param.id===i,E=["magicx-aia-segment","magicx-aia-segment--completed"];y&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&E.push("magicx-aia-segment--editing"),b.className=E.join(" "),b.style.letterSpacing=wo(p.value.length);let A=l?G(p.param.image_url):null;if(A){let P=S.createElement("span");P.className="magicx-aia-segment-image",P.setAttribute("contenteditable","false"),P.setAttribute("aria-hidden","true"),P.style.setProperty("--aia-chip-image",`url("${A}")`),b.appendChild(P),b.dataset.aiaImage=""}let D=!A&&a&&p.param.icon_svg?be(p.param.icon_svg):null;if(D){let P=S.createElement("span");P.className="magicx-aia-segment-icon",P.setAttribute("contenteditable","false"),P.setAttribute("aria-hidden","true"),P.innerHTML=D,b.appendChild(P),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),v.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===i&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=wo(p.value.length),b.textContent=p.value,v.appendChild(b)}else v.appendChild(S.createTextNode(p.value));e.replaceChildren(v),e.dataset.aiaTextLength=String(f),h!=null?L(e,Math.max(0,Math.min(h,f))):s&&Nn(e)&&L(e,f)}var mr='<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 Eo(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=mr,n}function gr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Po(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let o=t.getBoundingClientRect(),i=n.getBoundingClientRect();o.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function To(n,e){let{listboxId:t}=e,o=Ye(t);n.appendChild(o);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",i.setAttribute("data-aia-input-wrapper",""),n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),i.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",gr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),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,c=null;e.submitButton===void 0?(l=Eo(),i.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),i.appendChild(c));let d=new AbortController,{signal:u}=d,m=!1,g=0,h=()=>{let f=_e(s),b=f.length>0&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;e.handleChange(b)},S=()=>{let f=Y(s)?.node??null;if(!f||!s.contains(f))return null;let y=(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&_n(s,y)?null:y};if(i.addEventListener("click",f=>{f.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(g=performance.now(),h(),e.handleCaretAfterInput(_(s)))},{signal:u}),O(s).addEventListener("selectionchange",()=>{let f=Y(s);if(!f||!s.contains(f.node))return;let p=f.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()-g<50||e.handleCaretMove(_(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",f=>{let p=f,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){f.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(y)&&f.preventDefault()}},{signal:u}),s.addEventListener("paste",f=>{f.preventDefault();let p=(f.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=O(s),y=Re(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let x=b.createTextNode(p);y.insertNode(x),y.setStartAfter(x),me(s,y.startContainer,y.startOffset),h()},{signal:u}),s.addEventListener("keydown",f=>e.handleKeyDown(f),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",f=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;f.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 f=Y(s);(!f||!s.contains(f.node))&&me(s,s,0)}if(typeof ResizeObserver<"u"){let f=new ResizeObserver(()=>Po(s,a));f.observe(s),d.signal.addEventListener("abort",()=>f.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:o,submitButton:l,abort:d}}function Vt(n,e,t){let{input:o,inlinePillContainer:i,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;o.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?o.setAttribute("aria-activedescendant",u):o.removeAttribute("aria-activedescendant"),s){let f=!!e.text||e.completedParams.length>0;s.disabled=!f}let m=o.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==m;if(Ut({input:o,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0,showChipImages:t.showChipImages??!0}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?Ke(i,e.actionableSuggestions,0,l,!1,f,e.isActivePillSelected):Dt(i)}else Dt(i);Po(o,i),g?(o.focus(),L(o,e.caretOffset??e.text.length)):e.isFocused&&_e(o)!==e.text&&L(o,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:$(e.editingIdentified.type),required:!0,options:[]}:null,S=e.dropdownSuggestion??h??e.actionableSuggestions[0],v=fe(e);je(r,{suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:f=>d.set({activeDropdownIndex:f}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:f=>d.set({isFocused:f})})}function Kt(n){let e=n,t=new Set,o=[],i=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},o.push([e,a]),!i){i=!0;try{let l=0;for(let c=o.shift();c;c=o.shift()){if(++l>1e4)throw o.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let m of t)m(d,u)}}catch(l){throw o.length=0,l}finally{i=!1}}},subscribe:r=>(t.add(r),()=>{t.delete(r)})}}function Co(n,e){let t,o,i=r=>(r!==t&&(t=r,o=e(r)),o);return{get:()=>{let r=n.get();return{...r,...i(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...i(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let l={...a,...i(a)},c={...s,...i(s)};r(c,l)})}}var Qt=new WeakSet,Oo=new WeakMap;function Io(n){return n.nodeType===Node.DOCUMENT_NODE}function fr(n){return Io(n)?n:n.ownerDocument}function hr(n){let e=Oo.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let o=new t;return typeof o.replaceSync!="function"?null:(o.replaceSync(Lo),Oo.set(n,o),o)}catch{return null}}function Ao(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=Lo,e.appendChild(t)}function Ro(n){if(typeof document>"u")return;let e=n??document;if(Qt.has(e))return;let t=fr(e);if(Io(e)){let r=e.head??e.documentElement;if(!r)return;Ao(t,r),Qt.add(e);return}let o=hr(t),i=e.adoptedStyleSheets;o&&Array.isArray(i)?i.includes(o)||(e.adoptedStyleSheets=[...i,o]):Ao(t,e),Qt.add(e)}var Lo=`.aia-stack {
1
+ function et(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function $(n){let e=et(n);return e.length>0?e.join(" "):n}var J=["January","February","March","April","May","June","July","August","September","October","November","December"],Se=["S","M","T","W","T","F","S"],tn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],nn="aiaDate",on="aiaDay",Zt=n=>String(n).padStart(2,"0");function k(n){return`${n.getFullYear()}-${Zt(n.getMonth()+1)}-${Zt(n.getDate())}`}function tt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function qo(n){let e=tt(n).getTime()-tt(new Date).getTime();return Math.round(e/864e5)}function rn(n){let e=qo(n);return e>=0&&e<7?tn[n.getDay()]:Z(n)}function Z(n){return n.getFullYear()===new Date().getFullYear()?`${J[n.getMonth()]} ${n.getDate()}`:`${J[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function xe(n){if(!n)return null;let e=tn.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=tt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let o=J.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(o<0)return null;let i=Number(t[2]),r=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(r,o,i);return s.getMonth()!==o||s.getDate()!==i?null:s}function nt(n){return`${J[n.month]} ${n.year}`}function ot(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function sn(n){return{year:n.getFullYear(),month:n.getMonth()}}function it(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function en(){return{text:"",is_tappable:!1,kind:null}}function rt(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),o=[];for(let i=0;i<e;i++)o.push(en());for(let i=1;i<=t;i++){let r=new Date(n.year,n.month,i);o.push({text:rn(r),is_tappable:!0,kind:null,metadata:{[nn]:k(r),[on]:i}})}for(;o.length%Se.length!==0;)o.push(en());return o}function st(n){let e=xe(n);return e?k(e):null}function N(n){let e=n?.metadata?.[nn];return typeof e=="string"?e:null}function at(n){let e=n?.metadata?.[on];return typeof e=="number"?e:null}function Uo(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function an(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:J.findIndex(t=>t.toLowerCase().startsWith(e))}function Vo(n,e,t){let o=new Date(t.getFullYear(),n,e);if(o.getMonth()!==n||o.getDate()!==e)return null;let i=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(o>=i)return o;let r=new Date(t.getFullYear()+1,n,e);return r.getMonth()===n&&r.getDate()===e?r:null}function ln(n,e,t){let o=new Date(n,e,t);return o.getMonth()===e&&o.getDate()===t?o:null}function q(n,e={}){if(!n)return null;let t=e.today??new Date,o=Uo(n.trim().toLowerCase()).replace(/\s+/g," "),i=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(o);if(i){let l=ln(Number(i[1]),Number(i[2])-1,Number(i[3]));return l?k(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(o);if(r){let l=an(r[1]);if(l>=0)return ve(l,Number(r[2]),r[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(o);if(s){let l=an(s[2]);if(l>=0)return ve(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(o);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?ve(c-1,l,a[3],t):c>12&&l<=12?ve(l-1,c,a[3],t):null}return null}function ve(n,e,t,o){if(t){if(t.length!==4)return null;let r=ln(Number(t),n,e);return r?k(r):null}let i=Vo(n,e,o);return i?k(i):null}function lt(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:q(n.text,e)}var cn=" - ",ct="aiaDateRangeStart",ut="aiaDateRangeEnd";function le(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var dt=/^\d{4}-\d{2}-\d{2}$/;function dn(n){if(!dt.test(n))return null;let[e,t,o]=n.split("-").map(Number),i=new Date(e,t-1,o);return i.getMonth()===t-1&&i.getDate()===o?i:null}var Ko=/\s+(?:to|through|thru|until|til|till)\s+/g,Qo=/[-–—]/g;function Yo(n){let e=[];for(let t of[Ko,Qo]){t.lastIndex=0;let o=t.exec(n);for(;o!==null;)e.push([n.slice(0,o.index),n.slice(o.index+o[0].length)]),o=t.exec(n)}return e}function ee(n,e={}){if(!n)return null;let t=new Set,o=null;for(let[i,r]of Yo(n.trim())){let s=q(i.trim(),e);if(!s)continue;let a=q(r.trim(),e);!a||a<s||(t.add(`${s}|${a}`),o={start:s,end:a})}return t.size===1?o:null}function un(n){let e=dn(n.start),t=dn(n.end);return!e||!t?"":n.start===n.end?Z(e):`${Z(e)}${cn}${Z(t)}`}function pn(n,e){let t=le(n,e);return{text:un(t),is_tappable:!0,kind:null,metadata:{[ct]:t.start,[ut]:t.end}}}function de(n,e={}){let t=n?.metadata?.[ct],o=n?.metadata?.[ut];return typeof t=="string"&&typeof o=="string"&&dt.test(t)&&dt.test(o)?le(t,o):ee(n?.text,e)}function w(n){return n==="date"||n==="date-range"}var jo=new Set(["date","dates"]),zo=new Set(["range","ranges","span","period","window"]),mn=3;function Xo(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(ee(t.text)!==null?e.range+=1:q(t.text)!==null&&(e.single+=1));return e}function U(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Xo(n.options);if(t.single+t.range>=mn&&t.range>t.single)return"date-range";let o=et(n.type);return o.some(i=>jo.has(i))?o.some(i=>zo.has(i))?"date-range":"date":t.single>=mn?"date":"options"}var we=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 Jo="https://api.ai-autocomplete.com",Pe=`${Jo}/api/suggest`,gn=new WeakMap;function ce(n){return n?.type==="accessToken"}function Zo(n){if(!(!n||ce(n)))return n}function Ee(n){let e=gn.get(n.getAccessToken);return e||(e=new we(n),gn.set(n.getAccessToken,e)),e}function Te(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ce(n){let e=Zo(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ue(n){return n.map(e=>({type:e.type,value:e.text}))}var fn="skipped";function pe(n,e){if(e.length===0)return n;let t=new Set(n.map(i=>i.type)),o=e.filter(i=>!t.has(i.type)).map(i=>({placeholder:"",type:i.type,text:fn,kind:null}));return o.length>0?[...n,...o]:n}var ei="0.30.0",hn=!1;function ti(){return crypto.randomUUID()}function ni(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function oi(n,e,t,o,i,r,s,a,l){let c=e.find(u=>u.type==="contact"&&u.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof c=="number"?c:void 0;return{data:{raw_query:n,completed_params:pe(e.map(u=>ni(u,t)),a??[]),...r&&r.length>0&&{identified_params:ue(r)},...s&&s.length>0&&{recently_suggested:s},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:ti(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ei,session_id:o,source:i}}}async function bn(n,e,t,o,i){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:i})}async function yn(n,e,t){let o=t.apiConfig,i=!t.maskCompletedText,r=oi(n,e,i,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Te(o),a=o?.endpoint??Pe,l=JSON.stringify(r);if(ce(o)){let u=Ee(o),m=await u.getToken(),g=await bn(a,s,m,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await bn(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=Ce(o);!c&&!hn&&(hn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(s.Authorization=c);let d=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function R(n,e){let t=n,o={},i=[],r=[],s=0;for(let a of e){let l=(o[a.type]??0)+1;o[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&r.some(S=>h<S.end&&h+a.text.length>S.start);)h=t.indexOf(a.text,h+1);return h},m=u(s);if(m===-1&&(m=u(0)),m!==-1){t=t.slice(0,m)+d+t.slice(m+a.text.length);let g=d.length-a.text.length;for(let h of r)h.start>=m+a.text.length&&(h.start+=g,h.end+=g);r.push({start:m,end:m+d.length}),s=m>=s?m+d.length:s+g}i.push({...a,placeholder:d})}return{rawQuery:t,completedParams:i}}function F(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Oe(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function V(n,e,t){let o=n.slice(e);if(t||e===0||n[e-1]===" ")return o;let i=o.indexOf(" ");return i===-1?"":o.slice(i+1)}function Sn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),i=e.toLowerCase();for(let r=0;r<o.length;r++){let s=o.slice(r).join(" ");if(i.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function K(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let o=t.toLowerCase();return n.filter(i=>!i.is_tappable||i.text.toLowerCase().includes(o))}function te(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return n.find(i=>i.is_tappable&&i.text.toLowerCase()===o)??null}function xn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function vn(n,e){let t=0,o=e;for(let i of n)t+=i.value.length,i.type!=="text"&&(o=Math.max(o,t));return o}function wn(n,e){let t=0;for(let o of n){let i=t+o.value.length;if(o.type==="text"&&i>e&&o.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=i}return!0}function Pn(n,e){let t=[],o=new Set;for(let i of[...n,...e])i.type==="placeholder"||o.has(i.type)||(o.add(i.type),t.push({type:i.type,text:i.text}));return t}function En(n,e,t){if(n===e)return t;let o=Math.min(n.length,e.length),i=0;for(;i<o&&n[i]===e[i];)i++;if(i>=t)return t;let r=0;for(;r<o-i&&n[n.length-1-r]===e[e.length-1-r];)r++;return n.length-r<=t?t+(e.length-n.length):null}function pt(n,e){let t=[],o=[],i=0;for(let r of e){let s=n.indexOf(r.text,i);if(s===-1){o.push(r);continue}t.push({start:s,end:s+r.text.length,param:r}),i=s+r.text.length}return{located:t,missing:o}}function Tn(n,e,t){let o=[],i=[],r=0;for(let s of t){let a=n.indexOf(s.text,r);for(;a!==-1&&e.some(l=>a<l.end&&a+s.text.length>l.start);)a=n.indexOf(s.text,a+1);if(a===-1){i.push(s);continue}o.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:o,missing:i}}function Cn(n,e,t=[]){let o=pt(n,e).located,i=Tn(n,o,t).located,r=[...o.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...i.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),s=[],a=0;for(let c of r)c.start>a&&s.push({type:"text",value:n.slice(a,c.start)}),s.push(c.segment),a=c.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function On(n,e){let{located:t,missing:o}=pt(n,e);return{valid:t.map(i=>i.param),invalid:o}}function Ie(n,e,t){let o=pt(n,e).located,{located:i,missing:r}=Tn(n,o,t);return{valid:i.map(s=>s.param),invalid:r}}function ii(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var ri=100,si=300,ai=2,Ae=class{constructor(e,t,o,i,r,s,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=i;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(o=>{(o.text!==e||o.completedParams!==t)&&(e=o.text,t=o.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let o=new AbortController;this.abortController=o;let i=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:o.signal,isCurrent:()=>i===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?Pn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await yn(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(i!==this.fetchVersion)return;let c=(l.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),d=xn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],m=u[u.length-1],g=this.store.get().text,h,S;if(m?.state==="in_progress"){S=!0;let x=g.toLowerCase().lastIndexOf(m.text.toLowerCase());h=x!==-1?x:r}else S=!1,h=r;let f=d.filter(x=>x.type!=="placeholder")[0],p=null;if(f&&!w(U(f))){let x=V(g,h,S),P=te(f.options,x);P&&(p={id:crypto.randomUUID(),placeholder:"",type:f.type,text:P.text,value:P.value,kind:P.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:P.metadata,icon:P.icon,icon_svg:P.icon_svg,image_url:P.image_url},d=d.filter(I=>I!==f),this.callbacks.onAutoMatch?.({active:f,matched:P,rawQuery:e}))}let b=l.data.custom_fields??null,y=this.callbacks.productsForResponse?.(b);this.store.set(x=>{let P=p?[...x.completedParams,p]:x.completedParams,I=Ie(x.text,P,c).valid,D=new Set(s.skippedParams.map(C=>C.id)),E=new Set(x.skippedParams.filter(C=>!D.has(C.id)).map(C=>C.type));return{suggestions:E.size>0?d.filter(C=>C.type==="placeholder"||!E.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:S,identifiedParams:I,customFields:b,...y!==void 0?{products:y}:{},...p?{completedParams:P}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=ii(s);i===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(i===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}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(ai)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ri),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),si)}attemptFetch(e,t=!1){let o=this.store.get();if(!o.text&&o.completedParams.length===0)return this.doFetch("",[]),!0;let i=this.callbacks.consumerTick?.(o,e)??"no";if(i==="asked")return!0;if(i==="owns")return!1;let r=o.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=F(o.text,o.filterBase,r),a=V(o.text,s,o.filterInProgress),c=o.suggestions.filter(y=>y.type!=="placeholder")[0],d=w(o.activeFormatType),m=(c&&!d?K(c.options,a):[]).filter(y=>y.is_tappable),g=c&&!d?te(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!g&&h||Oe(o.text,o.completedParams.length,r))return!1;let{rawQuery:S,completedParams:v}=R(o.text,o.completedParams),f=S.length<o.lastRawQuery.length,p=Math.abs(S.length-o.lastRawQuery.length),b=t&&S!==o.lastRawQuery;return f||p>=e||b?(this.doFetch(S,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function li(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function Q(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&li(e)?e:n.ownerDocument??n}function O(n){return n.ownerDocument??n}function di(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function In(n){let e=Q(n);return!di(e)||typeof e.getSelection=="function"?null:e}function An(n){let e=In(n);if(!e)return null;let t=O(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function Rn(n,e){let t=n,o;try{o=t.getComposedRanges({shadowRoots:[e]})}catch{o=t.getComposedRanges(e)}return o.length>0?o[0]:null}function mt(n){let t=Q(n).getSelection?.();return t||(O(n).getSelection?.()??null)}function Y(n){let e=mt(n);if(!e||e.rangeCount===0)return null;let t=An(n);if(t){let o=Rn(e,t);return o?{node:o.startContainer,offset:o.startOffset,collapsed:o.startContainer===o.endContainer&&o.startOffset===o.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Re(n){let e=mt(n);if(!e||e.rangeCount===0)return null;let t=An(n);if(!t)return e.getRangeAt(0);let o=Rn(e,t);if(!o)return null;let i=O(n).createRange();return i.setStart(o.startContainer,o.startOffset),i.setEnd(o.endContainer,o.endOffset),i}function me(n,e,t){let o=mt(n);if(!o)return null;if(In(n))return o.collapse(e,t),o;let i=O(n).createRange();return i.setStart(e,t),i.collapse(!0),o.removeAllRanges(),o.addRange(i),o}function Le(n,e){let t=n?Q(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var De=2,ci="magicx-aia";function Ln(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function ui(n){let e=O(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let o=n;for(;o&&o!==e.body&&o!==e.documentElement;){let i=o.scrollWidth>o.clientWidth,r=o.scrollHeight>o.clientHeight;if(i||r){let s=t.getComputedStyle(o);if(i&&Ln(s.overflowX)||r&&Ln(s.overflowY))return o}if(o.classList.contains(ci))return null;o=o.parentElement}return null}function gt(n){let e=Re(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=ui(n);if(!t||typeof e.getBoundingClientRect!="function")return;let o=e.getBoundingClientRect();if(o.height===0)return;let i=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let r=i.left+t.clientLeft,s=r+t.clientWidth;o.right>s?t.scrollLeft+=o.right-s+De:o.left<r&&(t.scrollLeft-=r-o.left+De)}if(t.scrollHeight>t.clientHeight){let r=i.top+t.clientTop,s=r+t.clientHeight;o.bottom>s?t.scrollTop+=o.bottom-s+De:o.top<r&&(t.scrollTop-=r-o.top+De)}}var kn='[contenteditable="false"]',pi="strong[data-param-id]",ne;function mi(){if(ne!==void 0)return ne;let n=globalThis.Intl.Segmenter;if(!n)return ne=null,null;try{ne=new n(void 0,{granularity:"grapheme"})}catch{ne=null}return ne??null}function Me(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(kn))return!0;t=t.parentNode}return!1}function ke(n){return O(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Me(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function _e(n){let e=ke(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function ft(n){let e=ke(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function _(n){let e=Y(n);if(!e)return null;let t=e.node,o=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let i=t;if(Me(i,n)&&i!==n)return null;let r=0;for(let s=0;s<o&&s<i.childNodes.length;s++)r+=_n(i.childNodes[s],n);return r+Dn(i,n)}return t.nodeType!==Node.TEXT_NODE||Me(t,n)?null:Dn(t,n)+o}function _n(n,e){if(n.nodeType===Node.TEXT_NODE)return Me(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(kn))return 0;let o=0;for(let i of Array.from(t.childNodes))o+=_n(i,e);return o}function Dn(n,e){let t=ke(e),o=0,i=t.nextNode();for(;i;){if(i===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(i))return o;o+=i.data.length,i=t.nextNode()}return o}function L(n,e){let t=O(n),o=Math.max(0,Math.min(e,ft(n))),i=ke(n),r=0,s=null,a=0,l=i.nextNode(),c=null;for(;l;){let u=l.data.length;if(o<r+u){s=l,a=o-r;break}if(o===r+u){let m=i.nextNode();m?(s=m,a=0):(s=l,a=u);break}r+=u,c=l,l=i.nextNode()}let d=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===s.data.length?d.setStartAfter(u):d.setStart(s,a):d.setStart(s,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),me(n,d.startContainer,d.startOffset)&&(gi(n,d,o),gt(n))}function Mn(n,e){if(!n||!e.contains(n))return null;let o=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(pi)??null;return o&&e.contains(o)?o:null}function gi(n,e,t){let o=Mn(Y(n)?.node??null,n);if(o&&o!==Mn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${o.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function Nn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let o=_(n);return o!==null&&t===`${o}:${e}`}function Fn(n){return Q(n).activeElement===n}function ht(n){let e=_(n);return e==null?!1:e>=ft(n)}function bt(n,e){if(e<=0)return 0;let t=mi();if(!t)return e-1;let o=n.slice(0,e),i=0;for(let{index:r}of t.segment(o))r<e&&(i=r);return i}function j(n,e,t=[],o={}){let{rawQuery:i,completedParams:r}=R(n,e);return{query:n.trim(),raw_query:i,completed_params:pe(r,t),identified_params:ue(o.identifiedParams??[]),is_ready:o.isReady??!1,...o.customFields?{custom_fields:o.customFields}:{}}}function yt(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?ht(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function St(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?_(n):null}var Ne=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:i}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=i(),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 c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=yt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=w(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.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(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(t.activeDropdownIndex),g=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let m=yt(e.target,t),g=!!t.editingParam;if(!m&&!g)break;e.preventDefault();let h=w(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.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(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),L(u,m);break}yt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=St(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),L(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=St(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=St(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o,r):a&&a(j(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),m;if(u<0)m=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;m=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[m]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),L(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let i=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=i;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,t){let o=k(new Date),i=e.filteredOptions.findIndex(s=>N(s)===o);if(i>=0)return i;let r=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?r[r.length-1]:r[0])??0}stepDateDay(e,t){for(let o=e.activeDropdownIndex+t;o>=0&&o<e.filteredOptions.length;o+=t)if(e.filteredOptions[o]?.is_tappable){this.store.set({activeDropdownIndex:o});return}}stepDateWeek(e,t){let o=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[o]?.is_tappable?o:-1})}getTappableIndices(e){let o=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),i=Array.from({length:e},()=>[]);for(let r of o)i[r%e].push(r);return i.flat()}getEffectiveColumns(e){let t=Le(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let i=Le(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(i===t)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,o,i){let r=Le(i,`${o}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var Fe=class{constructor(e,t,o={}){this.store=e;this.getOverrides=t;this.callbacks=o;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let o=this.resolveTarget(e);if(!o||this.missCovers(o.type,o.query))return"no";let i=this.current;if(i&&i.key===o.key){if(i.query===o.query)return"owns";let r=Math.abs(o.query.length-i.query.length),s=o.query.length<i.query.length;if(t>1&&!s&&r<t)return"owns"}return this.ask(o),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(w(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let o=e.actionableSuggestions[0];return!o||!this.hasOverride(o.type)?null:{mode:"pill",key:o,type:o.type,suggestion:o,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],o=++this.version;if(!t||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 i=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:i};let r;try{r=t(e.query,i.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],o);return}if(Array.isArray(r)){this.commit(e,r,o);return}this.setSearch(e,"loading"),this.await(e,r,i.signal,o)}async await(e,t,o,i){let r;try{let s=await t;if(o.aborted||i!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(o.aborted||i!==this.version||fi(s))return;this.logOnce(s),r=[]}this.commit(e,r,i)}commit(e,t,o){if(o!==this.version)return;let i=this.resolveTarget(this.store.get());if(!i||i.key!==e.key)return;t.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:t}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:t};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}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let o=this.store.get().optionSearch;o&&o.type===e.type&&o.query===e.query&&o.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function fi(n){return n instanceof Error&&n.name==="AbortError"}var He=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),o=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=o.length)return;let i=o[e],r=o.filter((c,d)=>d!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=R(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:i.text,otherPills:r.map(d=>d.text)})}let a=[...s,i,...r],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Bn="/products/",Hn="https://relative.invalid";function hi(n){if(!n)return;let e;try{e=new URL(n,`${Hn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Hn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Wn(n){let e=hi(n.item_url)??(n.handle?`${Bn}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function xt(n){return(n?.items.matched??[]).map(Wn)}var Be=class{constructor(e,t,o=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=o;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return xt(e)}async run(e,t,o){if(!this.isEnabled())return;let i=this.getConfig();if(!i)return;if(e.trim().length===0){this.clear(o);return}let r=()=>t.aborted||!o()||!this.owns(i);try{let s=await i.fetch(e,t);if(r())return;let a=i.transform(s),l=Array.isArray(a)?a:[],c=i.limit!=null?l.slice(0,i.limit):l;if(r())return;this.commit(c)}catch(s){if(t.aborted||bi(s)||(this.logOnce(s),r()))return;this.clear(o)}}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 bi(n){return n instanceof Error&&n.name==="AbortError"}var We="(max-width: 768px)";var yi="var(--aia-option-row-height, 37px)",Si="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function Gn(n,e){return e?vt(1,Math.min(n,5)):vt(1,Math.min(n,4))}function vt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${yi} + ${Si})`}}function Pt(n,e){return!e&&n>=5}function Et(n,e,t,o){if(!(!e&&n>=5&&xi(t,o))){let s=Gn(n,e);return{...s,template:wt(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let r=6;return{...vt(2,3),template:wt(2),scrollHintIndices:n>r?[r-2,r-1]:[]}}function xi(n,e){return!n||n.length===0||e==null||e<=0||n.some(o=>o<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function Tt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let 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",t.appendChild(a)}n.appendChild(t);let o=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let i=getComputedStyle(n),r=n.clientWidth-(Number.parseFloat(i.paddingLeft)||0)-(Number.parseFloat(i.paddingRight)||0)-(Number.parseFloat(i.columnGap)||0);return{rowWidths:o,gridWidth:r}}function wt(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Ct(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(We).matches}function Ot(n,e){return!n||n.length!==e.length?!1:n.every((t,o)=>t.text===e[o].text)}function $n(n,e){let t=e.dropdownTrigger??"auto",o=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=o?n.isFocused:!0;return s&&a}if(t==="auto"){let a=o?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&c}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function ge(n){if(n.editingIdentified){let{type:t,anchor:o}=n.editingIdentified;return`identified:${t}@${o}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function qn(n){if(!n)return ot();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function vi(n){let e=xe(n);return e?sn(e):ot()}function Un(n,e){let t=Cn(n.text,n.completedParams,n.identifiedParams),o=n.suggestions.filter(T=>T.type!=="placeholder"),i=o[0],r=n.suggestions.filter(T=>T.type==="placeholder").map(T=>T.text).join(" "),s=F(n.text,Math.min(n.filterBase,n.text.length),r),l=s===0&&Oe(n.text,n.completedParams.length,r)?"":V(n.text,s,n.filterInProgress),c=i?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,m,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let T=n.editingParam.id,X=n.completedParams.some($o=>$o.id===T),ae=n.caretOffset??n.editingAnchor,Jt=X?"":n.text.slice(n.editingAnchor,ae);m=Jt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=K(n.editingParam.options,Jt)}else m=l.trim(),g=c,h=i?.type,u=K(c,l);let S=n.optionSearch,v=S!=null&&h!=null&&S.type===h;v&&S.status==="done"&&S.query===m&&(u=g);let f=v&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(T=>T.is_tappable));let b=n.editingIdentified,y=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:i,x=b?b.format:U(y),P=d&&w(x)?de(n.editingParam):null;P&&(x="date-range");let I=null,D=null;if(w(x)){let T=ge({...n,actionableSuggestions:o}),X=n.dateViewMonth;I=X&&X.key===T?{year:X.year,month:X.month}:b?qn(b.iso):P?qn(P.start):vi(n.editingParam?.text),u=rt(I);let ae=n.pendingRangeStart;x==="date-range"&&ae&&ae.key===T&&(D=ae.iso)}let E=T=>p?T.is_tappable:!0,A;if(d){let T=n.editingParam?.options??[];A=n.editingParam!=null&&T.filter(E).length===0}else A=i!=null&&c.filter(E).length===0;let C=$n({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||f,pillTapped:n.pillTapped,activePillHasNoOptions:A,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Ze=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable,M=n.skeletonOptions!==null&&n.skeletonRequested&&!n.isLoading&&!n.editingParam&&!n.inSelectionAnimation,z=n.isLoading&&!n.editingParam&&!n.inSelectionAnimation||f||M,Xt=z&&n.skeletonOptions!==null,Wo=Xt&&n.skeletonOptions?n.skeletonOptions:u,Go=Xt?n.skeletonSuggestion:null;return{segments:t,actionableSuggestions:o,filteredOptions:u,dropdownLoading:z,dropdownOptions:Wo,dropdownSuggestion:Go,skeletonExiting:M,activeFormatType:x,dateView:I,dateRangeStart:D,placeholderText:r,optionQuery:m,isSearchingOptions:f,isDropdownOpen:C,isActivePillSelected:Ze}}function Ge(n){return n.mode==="fresh"?wi(n):Pi(n)}function wi(n){let{text:e,completedParams:t,suggestions:o,filterBase:i,filterInProgress:r}=n,a=o.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=o.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),c=F(e,i,l),d=V(e,c,r),u=te(a.options,d);if(!u)return null;let m=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(m),h=g>=0?g:Math.max(0,e.length-u.text.length),S=h+u.text.length,v=e.slice(h,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,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:[...t,b],suggestions:o.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function Pi(n){let{text:e,completedParams:t,editingParam:o,editingAnchor:i,editingTail:r}=n;if(t.some(b=>b.id===o.id))return null;let s=e.slice(i,r),a=te(o.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=i+Math.max(0,c),u=d+a.text.length,m=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,S={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:m,value:a.value,kind:a.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},v=t.length,f=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,f);if(y!==-1){if(y>=g){v=b;break}f=y+t[b].text.length}}let p=[...t];return p.splice(v,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Vn(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let o=n.filterBase,i=n.text.slice(0,o),r=i.length===0&&n.text.length===0,s=i.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(i=`${n.placeholderText} `);let a=Sn(i,e.text);a>0&&(i=i.slice(0,i.length-a));let l=i.length>0&&i[i.length-1]!==" ",c=`${i}${l?" ":""}${e.text} `,d=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,value:e.value,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(S=>S.text!==e.text).map(S=>S.text)},consumedSuggestion:t,remainingActionable:h}}function $e(n){let e=w(n.activeFormatType)||n.filteredOptions.length===0?null:n.filteredOptions,t=n.editingParam,o=t?{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options}:n.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?o:null,skeletonRequested:!1}}function qe(n,e,t){let o=n.slice(0,e),i=n.slice(t),r=(o===""||o.endsWith(" "))&&i.startsWith(" ");return r&&(i=i.slice(1)),{text:o+i,removed:t-e+(r?1:0)}}var Ue=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let o=t.completedParams.find(s=>s.id===e);if(!o)return;let i=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,i);if(a!==-1){if(s.id===e){r=a;break}i=a+s.text.length}}r<0||this.deps.store.set({editingParam:o,editingAnchor:r,editingTail:r+o.text.length,caretOffset:r+o.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),o=t.editingParam,i=t.editingAnchor,r=t.editingTail;if(!o||i==null||r==null||!t.completedParams.some(l=>l.id===o.id))return!1;let{text:s}=e===""?qe(t.text,i,r):{text:t.text.slice(0,i)+e+t.text.slice(r)},a=i+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==o.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),o={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(o.editingParam=null,o.editingAnchor=null,o.editingTail=null,o.activeDropdownIndex=-1):t.editingTail!=null&&(o.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(o),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),o=t.editingParam,i=t.editingAnchor,r=t.editingTail;if(!o||i==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:o.options.filter(f=>f.text!==e.text).map(f=>f.text)});let s=t.text.slice(0,i),a=t.text.slice(r),l=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,m=u.length,g={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=t.completedParams.findIndex(f=>f.id===o.id),S=t.completedParams.filter(f=>f.id!==o.id),v=h>=0?Math.min(h,S.length):S.length;S.splice(v,0,g),this.deps.store.set({text:u,completedParams:S,newParamId:g.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...$e(t)}),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 t=Ge({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Ei=33,Ti=70,Ci=120,Oi=50,oe="data-aia-placeholder-leaving",ie=new WeakMap;function Ve(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Ii(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Qn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Yn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Qn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],o=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Yn(n,e),33+o)}function Kn(n,e){Qn(n,e,0),e.timer=setTimeout(()=>Yn(n,e),33)}function jn(n,e){let t=ie.get(n);if(e===""){t&&(Ve(t),ie.delete(n)),n.removeAttribute(oe),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Ii(n)){t&&Ve(t),n.removeAttribute(oe),ie.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let o={target:e,shown:0,timer:null},i=t&&t.shown>0?t:null;if(t&&Ve(t),ie.set(n,o),i){n.setAttribute(oe,""),o.timer=setTimeout(()=>{o.timer=null,n.removeAttribute(oe),n.isConnected&&Kn(n,o)},170);return}n.removeAttribute(oe),Kn(n,o)}function zn(n){let e=ie.get(n);e&&(Ve(e),ie.delete(n))}var Xn="https://ai-autocomplete.com";function It(n=Xn){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function At(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Jn=new WeakMap,Zn=new WeakSet;function H(n,e,t){if(Jn.set(n,t),Zn.has(n))return;Zn.add(n);let o=()=>Jn.get(n),i=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&n.contains(s)?s:null};e.onClick&&n.addEventListener("click",r=>{let s=i(r.target);s&&e.onClick?.(s,o(),r)}),e.onEnter&&n.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,o())},!0),e.preventMousedown&&n.addEventListener("mousedown",r=>r.preventDefault())}function re(n){return Number.parseInt(n.dataset.aiaIndex??"-1",10)}function B(n){n.offsetWidth}var Ai={selectedIso:null,selectedRange:null,rangeStart:null};function fe(n){if(!w(n.activeFormatType))return Ai;let e=n.editingIdentified;if(e){let{iso:o,isoEnd:i}=e;return{selectedIso:i?null:o,selectedRange:o&&i?le(o,i):null,rangeStart:n.dateRangeStart}}let t=de(n.editingParam);return{selectedIso:t?null:st(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function Rt(n){return n.pendingStart?le(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Lt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:o}=e,i=n===t||o!=null&&(n===o.start||n===o.end),r=o!=null&&n>o.start&&n<o.end;return{selected:i,inRange:r}}var eo="data-aia-key";function W(n,e,t){let o=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(eo);a!=null&&o.set(a,s)}let i=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);i.add(l);let c=o.get(l);c||(c=t.create(a,s),c.setAttribute(eo,l)),t.update?.(c,a,s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null),r.push(c)}for(let[s,a]of o)i.has(s)||a.remove();return r}function to(n,e){if(!e.interactive)return null;let t=e.options[re(n)];return t?.is_tappable?t:null}var Ri={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(n,e)=>{if(n.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(n.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let t=to(n,e);t&&(n.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(n,e)=>{n.hasAttribute("data-aia-date-cell")&&to(n,e)&&e.callbacks.onHighlight(re(n))}};function oo(n,e,t,o,i,r,s,a=!0){let l=n.querySelector(".magicx-aia-datepicker");if(!i||e.length===0){l?.remove();return}if(!l){l=Mi(),n.appendChild(l),B(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}H(l,Ri,{options:e,callbacks:s,interactive:a});let c=l.querySelector(".magicx-aia-datepicker-month");c&&(c.textContent=nt(i));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&Li(d,e,t,o,r)}function Li(n,e,t,o,i){let r=k(new Date),s=Rt({pendingStart:i.rangeStart,highlightedIso:N(e[t]),selected:i.selectedRange});W(n,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>Di(a),update:(a,l,c)=>{let d=N(l),u=Lt(d,{selectedIso:i.selectedIso,range:s}),m=c===t&&l.is_tappable;a.id=`${o}-option-${c}`,a.dataset.aiaIndex=String(c),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",d!=null&&d<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",d!=null&&d===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function Di(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=at(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let o=document.createElement("span");return o.className="magicx-aia-date-cell-number",o.textContent=String(t),e.appendChild(o),e}function Mi(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(no("prev","Previous month","\u2039"),t,no("next","Next month","\u203A"));let o=document.createElement("div");o.className="magicx-aia-datepicker-weekdays",o.setAttribute("aria-hidden","true");for(let r of Se){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,o.appendChild(s)}let i=document.createElement("div");return i.className="magicx-aia-datepicker-grid",i.setAttribute("data-aia-date-grid",""),n.append(e,o,i),n}function no(n,e,t){let o=document.createElement("button");return o.type="button",o.tabIndex=-1,o.className="magicx-aia-datepicker-nav",o.setAttribute(`data-aia-date-${n}`,""),o.setAttribute("aria-label",e),o.textContent=t,o.disabled=!0,o}var ki={itemSelector:"[data-aia-pill]",onClick:(n,e)=>{if(e.loading||n.disabled)return;let t=Number.parseInt(n.dataset.aiaPillIndex??"-1",10);t>=0&&e.onSelectPill(t)},preventMousedown:!0},io=[125,69];function ro(n,e){return e?1:n===0?.7:n===1?.4:.2}function Ke(n,e,t,o,i=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),H(a,ki,{onSelectPill:o,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<io.length;l++){let c=io[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${i?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(ro(l,!1)),a.appendChild(d)}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();W(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.disabled=!0,c},update:(l,c,d)=>{let u=l,m=s&&d===t&&!r,g=["magicx-aia-pill"];i&&g.push("magicx-aia-pill--rounded"),r&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(ro(d,m)),u.dataset.aiaPillIndex=String(d),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),B(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function Dt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var _i=32;function so(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,o=e.deltaX||0;if(!t||Math.abs(o)>=Math.abs(t))return null;let i=n.scrollWidth-n.clientWidth;if(i<=1)return null;let r=n.scrollLeft,s=t;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=n.clientWidth),Math.max(0,Math.min(i,r+s))}function Mt(n){let e=t=>{let o=so(n,t);o!==null&&(t.preventDefault(),n.scrollLeft=o)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var ao=Intl.Segmenter,lo=ao?new ao(void 0,{granularity:"grapheme"}):null;function kt(n){let e=n.trim().normalize("NFC").toUpperCase();if(lo)for(let t of lo.segment(e))return t.segment;return Array.from(e)[0]??"?"}var _t=new WeakMap,co=new WeakMap,Ni="Products";function uo(n,e,t,o,i,r="row",s="image"){let a=n.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",`${t}-products-label`);let c=document.createElement("div");c.className="magicx-aia-products-label",c.id=`${t}-products-label`,c.setAttribute("data-aia-products-label",""),c.textContent=Ni;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),Mt(d),a.append(c,d),n.appendChild(a)}a.setAttribute("data-aia-products-layout",r);let l=a.querySelector(".magicx-aia-products-row");if(l){W(l,e,{keyOf:c=>Fi(c),create:c=>Hi(c,o,i,s),update:(c,d,u)=>{c.id=`${t}-product-${u}`,c.dataset.aiaIndex=String(u),co.get(c)?.(s)}}),B(l);for(let c of l.querySelectorAll("[data-aia-product]")){let d=_t.get(c);d&&(_t.delete(c),d())}}}function Nt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let o of t)o.tabIndex=e?0:-1}function Fi(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Hi(n,e,t,o){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.tabIndex=0;let r=document.createElement("span");r.className="magicx-aia-product-media",r.setAttribute("aria-hidden","true");let s=n.imageUrl?.trim(),a=!!s,l=()=>{r.replaceChildren(),r.toggleAttribute("data-aia-product-placeholder",o==="image"),r.toggleAttribute("data-aia-product-initial",o==="initial"),o==="initial"&&(r.textContent=kt(n.title))};if(co.set(i,u=>{u!==o&&(o=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();i.appendChild(r);let c=document.createElement("span");if(c.className="magicx-aia-product-body",n.vendor){let u=document.createElement("span");u.className="magicx-aia-product-vendor",u.textContent=n.vendor,c.appendChild(u)}let d=document.createElement("span");if(d.className="magicx-aia-product-title",d.textContent=n.title,c.appendChild(d),n.price){let u=document.createElement("span");u.className="magicx-aia-product-price",u.textContent=n.price,c.appendChild(u)}return i.appendChild(c),_t.set(i,()=>{n.url&&(i.href=n.url),i.addEventListener("click",u=>{u.metaKey||u.ctrlKey||u.shiftKey||u.altKey||u.button!==0||(u.preventDefault(),e(n))})}),i.addEventListener("keydown",u=>{u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",u=>{u.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var Bi=80,Wi=150,Gi=280,$i=16,Ft="--aia-option-enter-delay";function Ht(n,e,t,o="below"){let i=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,n)/i);if(o!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/i));return Math.max(0,s-1-r)*80}function Bt(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}function G(n){if(!n)return null;let e=n.trim();if(e==="")return null;let t;try{t=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.href}function he(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var po={one:"item",other:"items"};function qi(n,e=po){let t=he(n);if(t===null)return null;let o=typeof e=="string"?e:n===1?e.one:e.other;return o===""?t:`${t} ${o}`}function Ui(n){return G(n.image_url)!==null}var mo="http://www.w3.org/2000/svg",Vi=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function Ki(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var Qi=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],Yi=/^[a-zA-Z0-9#.,%\s()-]+$/;function ji(n){let e=[];for(let t of Qi){let o=n.getAttribute(t);o===null||!Yi.test(o)||/url\s*\(/i.test(o)||e.push(`${t}: ${o.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function go(n){for(let e of Array.from(n.attributes))Ki(e.name,e.value)&&n.removeAttribute(e.name);ji(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Vi.has(t.localName)||t.namespaceURI!==mo?t.remove():go(t)}else e.remove()}function be(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==mo||e.getElementsByTagName("parsererror").length>0?null:(go(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function Wt(n){return n.text}var fo=new WeakMap;function zi(n,e,t){let o=e.length,i=Ct(),r=fo.get(n),s=t&&r&&Ot(r.options,e)?r.plan:null,a=!s&&!t&&Pt(o,i)?Tt(n):null,l=s??Et(o,i,a?.rowWidths??null,a?.gridWidth??null);return t||fo.set(n,{options:e,plan:l}),n.style.gridTemplateColumns=l.template,n.style.setProperty("--aia-grid-max-height",l.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((c,d)=>{c.classList.toggle("magicx-aia-option--scroll-hint",!t&&l.scrollHintIndices.includes(d))}),l.cols}function ho(n,e){if(e.loading||!e.interactive)return null;let t=e.options[re(n)];return t?.is_tappable?t:null}var Xi={itemSelector:"[data-aia-option]",onClick:(n,e)=>{let t=ho(n,e);t&&(n.classList.add("magicx-aia-option--pressed"),e.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(n,e)=>{ho(n,e)&&e.onHighlight(re(n))}};function bo(n,e,t,o,i,r,s,a="",l="below",c=!0,d=!0,u=!0,m=!0){let g=n.querySelector(".aia-grid");if(e.length===0){g?.remove();return}g||(g=document.createElement("div"),g.className="aia-grid magicx-aia-grid",g.setAttribute("data-scroll",""),g.style.setProperty("--aia-grid-min","250px"),g.style.setProperty("--aia-grid-max","1fr"),g.style.setProperty("--aia-grid-gap","0"),n.appendChild(g)),H(g,Xi,{options:e,onSelect:o,onHighlight:i,loading:s,interactive:m});let h=g.dataset.aiaGroup!==a;g.dataset.aiaGroup=a,Ji(g,e,t,r,s,{showIcons:c,showImages:d,showCounts:u});let S=zi(g,e,s);Zi(g,e.length,S,s,l),h&&(g.scrollTop=0)}function Ji(n,e,t,o,i,r){let s=i?"1":"0",a=n.dataset.aiaGroup??"",{showIcons:l,showImages:c,showCounts:d}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=c?h=>G(h.image_url)??"":()=>"",g=d?h=>he(h.item_count)??"":()=>"";W(n,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${g(h)}\0${s}\0${a}`,create:(h,S)=>{let v=er(h,i,r);return i||(v.dataset.aiaEntering=""),v},update:(h,S,v)=>{let f=v===t&&!i;h.id=`${o}-option-${v}`,h.dataset.aiaIndex=String(v),h.setAttribute("aria-selected",String(f)),h.classList.toggle("magicx-aia-option--highlighted",f)}})}function Zi(n,e,t,o,i){for(let r of n.querySelectorAll("[data-aia-entering]")){if(!o){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Ft,`${Ht(s,t,e,i)}ms`)}delete r.dataset.aiaEntering}}function er(n,e,{showIcons:t,showImages:o,showCounts:i}){let r=document.createElement("div");r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),e&&r.setAttribute("data-aia-loading",""),r.tabIndex=e||!n.is_tappable?-1:0;let s=["magicx-aia-option"];n.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=o?G(n.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.setAttribute("aria-hidden","true");let g=document.createElement("img");g.setAttribute("alt",""),g.setAttribute("loading","lazy"),g.setAttribute("decoding","async"),g.setAttribute("referrerpolicy","no-referrer"),g.setAttribute("draggable","false"),g.onerror=()=>{g.hidden=!0},g.src=l,m.appendChild(g),a.appendChild(m),r.dataset.aiaImage=""}let c=!l&&t&&n.icon_svg?be(n.icon_svg):null;if(c){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=c,a.appendChild(m),n.icon&&(r.dataset.aiaIcon=n.icon)}let d=document.createElement("span");if(d.className="magicx-aia-option-text",d.textContent=Wt(n),a.appendChild(d),n.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=n.tag,a.appendChild(m)}let u=i?he(n.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(n.item_count)}return r.appendChild(a),r}var yo="magicx-aia-scroll-arrow",So="data-aia-scroll-arrow",se="data-aia-visible",xo=1e3,vo=160,wo="--aia-scroll-arrow-bottom",Po="Scroll down for more options",tr="[data-aia-products-label]",nr=4,or=8,ir=240;function rr(n,e,t,o){let i=n.scrollTop,r=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!r||s||Gt(n)){n.scrollTop=i+e,o();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/ir),u=1-(1-d)*(1-d);n.scrollTop=i+e*u,d<1?r.call(t,c):o()};r.call(t,c)}function sr(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let o=n.createElementNS(e,"path");return o.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(o),t}function Eo(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=yo,e.setAttribute(So,""),e.setAttribute("aria-label",Po),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(sr(n)),e}function ar(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Gt(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function $t({dropdown:n,grid:e,button:t}){let o=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),i=!1;t.disabled=!0;let r=null,s=null,a=null,l=null,c=p=>{if(p){if(t.hasAttribute(se))return;if(t.setAttribute(se,""),t.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),Gt(e)){t.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&t.hasAttribute(se)&&(t.disabled=!1)},xo)}else t.removeAttribute(se),t.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,t.disabled=!0},d=p=>{let b=0,y=p;for(;y&&y!==n;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=n.querySelector(tr),b;if(p){let y=d(p)+p.offsetHeight/2;b=n.clientHeight-y-t.offsetHeight/2}else{let y=d(e),x=o&&Number.parseFloat(o.getComputedStyle(e).paddingBottom)||0;b=n.clientHeight-(y+e.offsetHeight)+(x>0?0:or)}t.style.setProperty(wo,`${Math.max(0,Math.round(b))}px`)},m=()=>{if(i||s!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,b=e.scrollHeight-e.clientHeight-e.scrollTop;c(!p&&b>nr)},g=()=>{if(i)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,c(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=Gt(e)?0:Bt(b,ar(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{i||s!==null||(c(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},vo))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),v=()=>{let p=o?(Number.parseFloat(o.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(o.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-p);rr(e,b,o,h)};t.addEventListener("mousedown",S),t.addEventListener("click",v);let f=null;return o&&typeof o.ResizeObserver=="function"&&(f=new o.ResizeObserver(()=>{u(),m()}),f.observe(e)),g(),{update:g,destroy(){i||(i=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,t.disabled=!0,e.removeEventListener("scroll",h),t.removeEventListener("mousedown",S),t.removeEventListener("click",v),f?.disconnect(),t.removeAttribute(se),t.setAttribute("aria-hidden","true"))}}}var lr=[159,119,164];function Ye(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}var Qe=new WeakMap;function dr(n,e){let t=Qe.get(n);if(t||(t={button:Eo(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Qe.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=$t({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function qt(n){let e=Qe.get(n);e&&(e.controller?.destroy(),Qe.delete(n))}function je(n,e){let{filteredOptions:t,activeIndex:o,isOpen:i,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:m}=e,g=s.length>0,h=a&&g,S=t.length>0,v=e.products.length>0,f=i&&(S||h||r||v);if(f?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),r?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!f){Nt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products"),n.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let p=n.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),n.appendChild(p));let b=e.showSkipButton&&g&&!e.isInputEmpty,y=h||r&&a||b,x=p.querySelector(".magicx-aia-pill-bar");if(y){x||(x=document.createElement("div"),x.className="magicx-aia-pill-bar aia-cluster",x.setAttribute("data-nowrap",""),x.setAttribute("data-aia-pillbar",""),p.insertBefore(x,p.firstChild));let M=x.querySelector(".magicx-aia-pill-scroll");M||(M=document.createElement("span"),M.className="magicx-aia-pill-scroll",M.setAttribute("data-aia-pill-scroll",""),x.insertBefore(M,x.firstChild)),Ke(M,a?s:[],0,u,!0,r&&a,l),pr(x,b,r||e.skipDisabled,s[0],m)}else x&&x.remove();let P=e.suggestions[0],I=P?`${P.type} ${P.text}`:"",D=w(e.formatType),E=D&&!r;bo(p,D?[]:t,o,c,d,e.listboxId,r,I,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),dr(n,p.querySelector(".aia-grid")),oo(p,E?t:[],o,e.listboxId,E?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let A=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||D)){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let M of lr){let z=document.createElement("span");z.className="magicx-aia-skeleton-bar",z.style.width=`${M}px`,A.appendChild(z)}p.appendChild(A)}}else A&&A.remove();uo(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),Nt(n,!0);let C=p.querySelector(".magicx-aia-footer")??gr(),Ze=o>=0&&!!t[o]?.is_tappable;mr(C,At(Ze,e.isInputEmpty)),C.isConnected||p.appendChild(C),cr(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function cr(n,e){let t=e.map(o=>n.querySelector(`:scope > ${o}`)).filter(o=>o!==null);for(let o=0;o<t.length;o++)n.children[o]!==t[o]&&n.insertBefore(t[o],n.children[o]??null)}var ur={itemSelector:".magicx-aia-skip",onClick:(n,e)=>{e.loading||e.onSkip()}};function pr(n,e,t,o,i){H(n,ur,{onSkip:i,loading:t});let r=n.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,n.appendChild(r),B(r)),r.setAttribute("aria-label",o?`Skip ${o.text}`:"Skip"),r.disabled=t}function mr(n,{key:e,hint:t}){let o=n.querySelector(".magicx-aia-footer-key"),i=n.querySelector(".magicx-aia-footer-hint");!o||!i||(o.textContent!==e&&(o.textContent=e),i.textContent!==t&&(i.textContent=t))}function gr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.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 t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let o=document.createElement("kbd");o.className="magicx-aia-footer-key",o.textContent="tab";let i=document.createElement("span");i.className="magicx-aia-footer-hint",i.textContent="to select",t.append(o,i);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=It(),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(t,r),n.append(e),n}function To(n,e){let t=Ye(e.listboxId);return n.appendChild(t),{dropdown:t}}function Ut(n,e,t){let o=fe(e);je(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:$(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:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",productImageFallback:t.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:o.selectedIso,selectedDateRange:o.selectedRange,dateRangeStart:o.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var fr=6,hr=.3;function Co(n){return n<=0?"0px":`${(-Math.min(hr,2*fr/n)).toFixed(3)}px`}function Vt(n){let{input:e,segments:t,newParamId:o,editingParamId:i,placeholderText:r,isFocused:s}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",jn(e,c?r:"");let d=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?G(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",g=e.dataset.editingParamId??"";if(d===u&&(o??"")===m&&(i??"")===g)return;if(d===u){e.dataset.newParamId=o??"",e.dataset.editingParamId=i??"";for(let p of e.querySelectorAll("strong[data-param-id]")){let b=p.dataset.paramId,y=p.dataset.seg==="completed"&&b===o;p.classList.toggle("magicx-aia-shimmer-revealed",y),p.classList.toggle("magicx-aia-shimmer-sweep",y),p.classList.toggle("magicx-aia-segment--editing",b===i)}return}let h=s?_(e):null;e.dataset.segKey=d,e.dataset.newParamId=o??"",e.dataset.editingParamId=i??"";let S=O(e),v=S.createDocumentFragment(),f=0;for(let p of t)if(f+=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===o,x=p.param.id===i,P=["magicx-aia-segment","magicx-aia-segment--completed"];y&&P.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&P.push("magicx-aia-segment--editing"),b.className=P.join(" "),b.style.letterSpacing=Co(p.value.length);let I=l?G(p.param.image_url):null;if(I){let E=S.createElement("span");E.className="magicx-aia-segment-image",E.setAttribute("contenteditable","false"),E.setAttribute("aria-hidden","true"),E.style.setProperty("--aia-chip-image",`url("${I}")`),b.appendChild(E),b.dataset.aiaImage=""}let D=!I&&a&&p.param.icon_svg?be(p.param.icon_svg):null;if(D){let E=S.createElement("span");E.className="magicx-aia-segment-icon",E.setAttribute("contenteditable","false"),E.setAttribute("aria-hidden","true"),E.innerHTML=D,b.appendChild(E),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),v.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===i&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=Co(p.value.length),b.textContent=p.value,v.appendChild(b)}else v.appendChild(S.createTextNode(p.value));e.replaceChildren(v),e.dataset.aiaTextLength=String(f),h!=null?L(e,Math.max(0,Math.min(h,f))):s&&Fn(e)&&L(e,f)}var br='<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 Oo(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=br,n}function yr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Io(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let o=t.getBoundingClientRect(),i=n.getBoundingClientRect();o.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ao(n,e){let{listboxId:t}=e,o=Ye(t);n.appendChild(o);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",i.setAttribute("data-aia-input-wrapper",""),n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),i.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",yr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),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,c=null;e.submitButton===void 0?(l=Oo(),i.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),i.appendChild(c));let d=new AbortController,{signal:u}=d,m=!1,g=0,h=()=>{let f=_e(s),b=f.length>0&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;e.handleChange(b)},S=()=>{let f=Y(s)?.node??null;if(!f||!s.contains(f))return null;let y=(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&Nn(s,y)?null:y};if(i.addEventListener("click",f=>{f.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(g=performance.now(),h(),e.handleCaretAfterInput(_(s)))},{signal:u}),O(s).addEventListener("selectionchange",()=>{let f=Y(s);if(!f||!s.contains(f.node))return;let p=f.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()-g<50||e.handleCaretMove(_(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",f=>{let p=f,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){f.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(y)&&f.preventDefault()}},{signal:u}),s.addEventListener("paste",f=>{f.preventDefault();let p=(f.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=O(s),y=Re(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let x=b.createTextNode(p);y.insertNode(x),y.setStartAfter(x),me(s,y.startContainer,y.startOffset),h()},{signal:u}),s.addEventListener("keydown",f=>e.handleKeyDown(f),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",f=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;f.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 f=Y(s);(!f||!s.contains(f.node))&&me(s,s,0)}if(typeof ResizeObserver<"u"){let f=new ResizeObserver(()=>Io(s,a));f.observe(s),d.signal.addEventListener("abort",()=>f.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:o,submitButton:l,abort:d}}function Kt(n,e,t){let{input:o,inlinePillContainer:i,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;o.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?o.setAttribute("aria-activedescendant",u):o.removeAttribute("aria-activedescendant"),s){let f=!!e.text||e.completedParams.length>0;s.disabled=!f}let m=o.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==m;if(Vt({input:o,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0,showChipImages:t.showChipImages??!0}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?Ke(i,e.actionableSuggestions,0,l,!1,f,e.isActivePillSelected):Dt(i)}else Dt(i);Io(o,i),g?(o.focus(),L(o,e.caretOffset??e.text.length)):e.isFocused&&_e(o)!==e.text&&L(o,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:$(e.editingIdentified.type),required:!0,options:[]}:null,S=e.dropdownSuggestion??h??e.actionableSuggestions[0],v=fe(e);je(r,{suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",productImageFallback:t.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:f=>d.set({activeDropdownIndex:f}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:f=>d.set({isFocused:f})})}function Qt(n){let e=n,t=new Set,o=[],i=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},o.push([e,a]),!i){i=!0;try{let l=0;for(let c=o.shift();c;c=o.shift()){if(++l>1e4)throw o.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let m of t)m(d,u)}}catch(l){throw o.length=0,l}finally{i=!1}}},subscribe:r=>(t.add(r),()=>{t.delete(r)})}}function Ro(n,e){let t,o,i=r=>(r!==t&&(t=r,o=e(r)),o);return{get:()=>{let r=n.get();return{...r,...i(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...i(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let l={...a,...i(a)},c={...s,...i(s)};r(c,l)})}}var Yt=new WeakSet,Lo=new WeakMap;function Mo(n){return n.nodeType===Node.DOCUMENT_NODE}function Sr(n){return Mo(n)?n:n.ownerDocument}function xr(n){let e=Lo.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let o=new t;return typeof o.replaceSync!="function"?null:(o.replaceSync(_o),Lo.set(n,o),o)}catch{return null}}function Do(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=_o,e.appendChild(t)}function ko(n){if(typeof document>"u")return;let e=n??document;if(Yt.has(e))return;let t=Sr(e);if(Mo(e)){let r=e.head??e.documentElement;if(!r)return;Do(t,r),Yt.add(e);return}let o=xr(t),i=e.adoptedStyleSheets;o&&Array.isArray(i)?i.includes(o)||(e.adoptedStyleSheets=[...i,o]):Do(t,e),Yt.add(e)}var _o=`.aia-stack {
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--aia-stack-space, 0.5rem);
@@ -701,6 +701,16 @@ function et(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
701
701
  the same media fill, so a card without art reads as "no photo" instead of
702
702
  broken. The pictogram is inlined as a data URI so the placeholder needs no
703
703
  network and no asset pipeline; --aia-product-placeholder-image swaps it. */
704
+ .magicx-aia-product-media:where([data-aia-product-initial]) {
705
+ display: flex;
706
+ align-items: center;
707
+ justify-content: center;
708
+ color: var(--aia-product-title-color, var(--aia-option-color-selected, currentColor));
709
+ font-size: 24px;
710
+ font-weight: 600;
711
+ line-height: 1;
712
+ }
713
+
704
714
  .magicx-aia-product-media[data-aia-product-placeholder]::after {
705
715
  content: "";
706
716
  position: absolute;
@@ -1210,6 +1220,42 @@ function et(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
1210
1220
  --aia-option-row-height: calc(var(--aia-option-image-size, 40px) + 16px);
1211
1221
  }
1212
1222
 
1223
+ /* A row without a picture, in a grid where other rows have one, lines up
1224
+ with them: it becomes the same centred flex row, its icon sits centred in a
1225
+ tile-sized box, and a row with no icon either is indented by the tile and
1226
+ its gap, so every option's text starts at the same x. Grids with no
1227
+ pictures keep the inline icon and hanging indent above. The text is left
1228
+ to size itself: letting it grow here would out-rank the loading-bar rule
1229
+ that makes a skeleton bar hug its text. */
1230
+ [data-aia-group]:has(.magicx-aia-option-image)
1231
+ .magicx-aia-option-content:not(:has(.magicx-aia-option-image)) {
1232
+ display: flex;
1233
+ flex: 1 1 auto;
1234
+ align-items: center;
1235
+ gap: var(--aia-option-image-gap, 12px);
1236
+ min-width: 0;
1237
+ min-height: var(--aia-option-image-size, 40px);
1238
+ padding-left: 0;
1239
+ text-indent: 0;
1240
+ }
1241
+
1242
+ [data-aia-group]:has(.magicx-aia-option-image)
1243
+ .magicx-aia-option-content:not(:has(.magicx-aia-option-image))
1244
+ .magicx-aia-option-icon {
1245
+ flex: 0 0 auto;
1246
+ justify-content: center;
1247
+ width: var(--aia-option-image-size, 40px);
1248
+ height: var(--aia-option-image-size, 40px);
1249
+ margin-right: 0;
1250
+ }
1251
+
1252
+ [data-aia-group]:has(.magicx-aia-option-image)
1253
+ .magicx-aia-option-content:not(:has(.magicx-aia-option-image)):not(
1254
+ :has(.magicx-aia-option-icon)
1255
+ ) {
1256
+ padding-left: calc(var(--aia-option-image-size, 40px) + var(--aia-option-image-gap, 12px));
1257
+ }
1258
+
1213
1259
  @keyframes magicx-aia-option-skeleton-pulse {
1214
1260
  0%,
1215
1261
  100% {
@@ -2127,5 +2173,5 @@ function et(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
2127
2173
  background: var(--aia-surface, #ffffff);
2128
2174
  }
2129
2175
  }
2130
- `;var ze=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(o){this.report(e,o,e);return}}runListener(e,t,o=e){try{return t(),!0}catch(i){return this.report(e,i,o),!1}}report(e,t,o){this.reported.has(o)||(this.reported.add(o),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var Xe=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let o=`${String(e)}#${++this.registrationCount}`,i=(...s)=>t(...s);this.keys.set(i,o);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let o=this.listeners[e];if(!o)return!0;let i=!0;for(let r of o)this.boundary.runListener(String(e),()=>r(...t),this.keys.get(r)??String(e))||(i=!1);return i}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Je=class{constructor(){this.timers=new Map}schedule(e,t,o){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),t()},o);this.timers.set(e,i)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ye=class{constructor(e,t="auto",o){this.container=e;this.mode=t;this.onResolve=o;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function br(n){return(n??Ee).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function yr(n){return ce(n)?`Bearer ${await Pe(n).getToken()}`:Ce(n)}async function Do(n){try{let e=br(n.apiConfig?.endpoint),t=Te(n.apiConfig),o=await yr(n.apiConfig);o&&(t.Authorization=o);let i=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:i})}catch{}}var Sr="newParam",Mo="suggestionRemoval",xr="selectionAnimation",Yt="skeletonExit",vr=650,wr=0;function Er(){return`:ac-${++wr}:`}var ko=170,Pr=100;function _o(){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 jt=class{constructor(e,t={}){this.inputStore=Kt(_o());this._listboxId=Er();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Je;this.boundary=new ze;this.subscriberCount=0;this.emitter=new Xe(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Co(this.inputStore,o=>qn(o,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new He(this.store,{onPillSelected:({rawQuery:o,selectedPill:i,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:i,other_pills:r})}}),this.reEdit=new Ue({store:this.store,scheduleSetCursor:o=>this.scheduleSetCursor(o),fireTelemetry:(o,i)=>this.fireTelemetry(o,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Be(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Fe(this.store,()=>this.opts.optionOverrides,{onAnswer:o=>{o==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(o,i)=>{o==="pill"&&i.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Ie(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:o,signal:i,isCurrent:r})=>{this.productsController.run(o,i,r).catch(()=>{})},onAutoMatch:({active:o,matched:i,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:i.text,other_options:(o.options??[]).filter(s=>s.text!==i.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:o=>this.productsController.forResponse(o),consumerTick:(o,i)=>this.optionSource.tick(o,i)}),this.keyboardController=new Ne(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:o=>this.selectOption(o),removeParamAtCaret:o=>this.removeParamAtCaret(o),startEditingParamAtCaret:o=>this.startEditingParamAtCaret(o),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((o,i)=>{o.text!==i.text&&this.emitter.emit("change",o.text),o.completedParams!==i.completedParams&&this.emitter.emit("paramsChange",o.completedParams),o.isFocused!==i.isFocused&&(o.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",o)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.subscribeSkeletonMirror(),this.unsubscribers.push(this.store.subscribe((o,i)=>{if(o.text===i.text&&o.completedParams===i.completedParams||o.identifiedParams.length===0)return;let{valid:r,invalid:s}=Ae(o.text,o.completedParams,o.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((o,i)=>{if(o.identifiedParams===i.identifiedParams)return;let r=o.editingIdentified;if(!r||o.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of o.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(o=>{let i=o.pendingRangeStart;!i||i.key===ge(o)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((o,i)=>{let r=o.pendingSpan;if(!r||o.text===i.text&&o.completedParams===i.completedParams&&o.identifiedParams===i.identifiedParams)return;let s=r.anchor;if(o.text!==i.text){let l=En(i.text,o.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}o.text.slice(s).trim().length===0||vn(o.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(Ro(this.opts.styleRoot??Q(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({..._o(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}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&&(jn(this.domRefs.input),$t(this.domRefs.dropdown)),this.dropdownRefs&&$t(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let o of this.store.get().segments){let i=t;if(t+=o.value.length,o.type!=="text"&&e>i&&e<=t)return{kind:o.type,param:o.param,start:i,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(o=>o.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(o=>o.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:o}=this.store.get(),{start:i,end:r}=t;if(e===r){let{text:l,removed:c}=qe(o,i,r);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>i?Math.max(i,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let s=bt(o,e),a=o.slice(0,s)+o.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),L(t.input,e);else{let o=this.opts.setCursor;o&&this.boundary.runListener("setCursor",()=>o(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let o=t.identifiedParams.find(d=>d.id===e);if(!o)return!1;let i=U(o);if(!w(i))return!1;let r=ee(o.text),s=i==="date-range"||r?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+o.text.length;return this.store.set({editingIdentified:{id:e,type:o.type,anchor:l,tail:c,text:o.text,iso:r?r.start:lt(o),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){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 t=this.store.get();if(!w(t.activeFormatType)||!t.dateView)return;let o=it(t.dateView,e);this.store.set({dateViewMonth:{...o,key:ge(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),o=e.suggestions.filter(a=>a.type!=="placeholder");if(o.length===0)return;let i=o[0],r=o.slice(1),s=e.skippedParams.some(a=>a.type===i.type);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:i.type,suggestionPlaceholder:i.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 t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(o=>{this.boundary.runListener("subscribe",()=>e(o),t)})}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,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,o=this.opts.showProducts,i=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==i&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==o)&&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.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 t=this.store.get();if(t.activeFormatType==="date-range"){let i=N(e);if(i){let r=t.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:i,key:ge(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(un(r,i));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.timers.clear(Yt),this.reEdit.selectOption(e);return}let o=Un(t,e);if(o){if(this.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:o.telemetry.selectedOption,other_options:w(t.activeFormatType)?[]:o.telemetry.otherOptions}),this.timers.clear(Yt),this.store.set({...o.patch,...$e(t)}),this.startSelectionAnimationTimer(),this.timers.clear(Mo),o.remainingActionable>0){let i=o.consumedSuggestion;this.timers.schedule(Mo,()=>{this.store.get().suggestions.includes(i)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==i)}))},ko)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(xr,()=>this.store.set({inSelectionAnimation:!1}),ko)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let o=this.resolveSource();Do({source:o,sessionId:this.sessionId,type:e,queryData:t,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 ye(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={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 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.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=To(this.container,t);let o=()=>{this.domRefs&&Vt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(o),this.subscribeViewportBreakpoint(o),Vt(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={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 optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=vo(this.container,t);let o=()=>{this.dropdownRefs&&qt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(o),this.subscribeViewportBreakpoint(o),qt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(We),o=()=>e();t.addEventListener("change",o),this.unsubscribers.push(()=>t.removeEventListener("change",o))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,t)=>{if(!e.skeletonOptions)return;if(!t.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!t.isLoading||e.isLoading)return;let o={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(o);return}this.timers.schedule(Yt,()=>this.store.set(o),Pr)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Sr,()=>this.store.set({newParamId:null}),vr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:i}=Cn(e,t.completedParams);i.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 t=F(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),o=xn(e.segments,t);e.text.slice(o).trim().length!==0&&this.store.set({pendingSpan:{anchor:o,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 t=e.caretOffset??e.editingAnchor,o=e.text.slice(e.editingAnchor,t);K(e.editingParam.options,o).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:o}=R(e.text,e.completedParams);this.fetchController.doFetch(t,o)}commitIdentifiedDate(e){let t=this.store.get(),o=t.editingIdentified;if(!o)return;if(t.text.slice(o.anchor,o.tail)!==o.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let i=t.text.slice(0,o.anchor),r=t.text.slice(o.tail),s=o.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=r.length===0||r[0]!==" "?`${s} `:s,c=i+l+r,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:o.type,text:s,value:e.value,kind:e.kind,suggestionType:o.type,suggestionPlaceholder:$(o.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(m=>m.id!==o.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(w(t.activeFormatType))return;let o=Ge({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});o&&this.store.set(o.patch)}};export{jt as AIAutocomplete,zn as ATTRIBUTION_URL,ut as DATE_RANGE_META_END,ct as DATE_RANGE_META_START,ao as DEFAULT_OPTION_COUNT_UNIT,ye as ModeController,We as OPTIONS_GRID_MOBILE_QUERY,Nt as OPTION_ENTER_DELAY_VAR,Ni as OPTION_ENTER_FADE_MS,Fi as OPTION_ENTER_RISE_MS,Hi as OPTION_ENTER_RISE_PX,_i as OPTION_ENTER_STAGGER_MS,wi as PLACEHOLDER_FADE_OUT_MS,oe as PLACEHOLDER_LEAVING_ATTR,Ei as PLACEHOLDER_SWAP_GAP_MS,xi as PLACEHOLDER_TYPE_MS,vi as PLACEHOLDER_WORD_PAUSE_MS,Hn as PRODUCT_PATH_PREFIX,Li as PRODUCT_ROW_PX_PER_LINE,dn as RANGE_SEPARATOR,fo as SCROLL_ARROW_ATTR,yo as SCROLL_ARROW_BOTTOM_VAR,go as SCROLL_ARROW_CLASS,ho as SCROLL_ARROW_FADE_MS,So as SCROLL_ARROW_LABEL,bo as SCROLL_ARROW_SCROLL_IDLE_MS,se as SCROLL_ARROW_VISIBLE_ATTR,gn as SKIPPED_PARAM_TEXT,Se as WEEKDAY_LABELS,it as addMonths,Mt as attachProductRowWheel,Gt as attachScrollArrow,At as buildAttributionUrl,rt as buildDateOptions,R as buildQuery,j as buildSubmitResult,at as cellDay,N as cellIso,Wn as computeOptionsGridLayout,Kt as createStore,ht as cursorIsAtEnd,Lt as dateCellMarks,fe as dateSelectionFor,_e as extractPlainText,Z as formatAbsoluteDate,on as formatDate,cn as formatDateRange,he as formatOptionCount,_ as getCursorOffset,It as getFooterHint,$ as identifiedParamLabel,w as isCalendarFormat,Ct as isOptionsGridMobileViewport,k as isoDate,Tt as measureOptionsGrid,nt as monthLabel,Et as needsOptionsGridMeasurement,Bi as optionCountLabel,Ft as optionEnterDelayMs,Wi as optionHasImage,G as optionImageSrc,Bt as optionLabel,Ht as optionsEntranceDurationMs,wt as optionsGridTemplateColumns,xe as parseDate,q as parseLooseDate,ee as parseLooseDateRange,ft as plainTextLength,Pt as planOptionsGrid,bt as previousGraphemeBoundary,Bn as productFromMatchedItem,ro as productRowWheelTarget,xt as productsFromCustomFields,Ut as renderEditableContent,U as resolveFormatType,lt as resolveIdentifiedDate,Ot as sameOptionRows,be as sanitizeOptionIconSvg,gt as scrollCaretIntoView,st as selectedIsoFromText,de as selectedRangeFor,L as setCursorOffset,ue as toWireIdentifiedParams,Rt as visibleDateRange,pe as withSkippedParams};
2176
+ `;var ze=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(o){this.report(e,o,e);return}}runListener(e,t,o=e){try{return t(),!0}catch(i){return this.report(e,i,o),!1}}report(e,t,o){this.reported.has(o)||(this.reported.add(o),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var Xe=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let o=`${String(e)}#${++this.registrationCount}`,i=(...s)=>t(...s);this.keys.set(i,o);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let o=this.listeners[e];if(!o)return!0;let i=!0;for(let r of o)this.boundary.runListener(String(e),()=>r(...t),this.keys.get(r)??String(e))||(i=!1);return i}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Je=class{constructor(){this.timers=new Map}schedule(e,t,o){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),t()},o);this.timers.set(e,i)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ye=class{constructor(e,t="auto",o){this.container=e;this.mode=t;this.onResolve=o;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function vr(n){return(n??Pe).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function wr(n){return ce(n)?`Bearer ${await Ee(n).getToken()}`:Ce(n)}async function No(n){try{let e=vr(n.apiConfig?.endpoint),t=Te(n.apiConfig),o=await wr(n.apiConfig);o&&(t.Authorization=o);let i=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:i})}catch{}}var Pr="newParam",Fo="suggestionRemoval",Er="selectionAnimation",jt="skeletonExit",Tr=650,Cr=0;function Or(){return`:ac-${++Cr}:`}var Ho=170,Ir=100;function Bo(){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,t={}){this.inputStore=Qt(Bo());this._listboxId=Or();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Je;this.boundary=new ze;this.subscriberCount=0;this.emitter=new Xe(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Ro(this.inputStore,o=>Un(o,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new He(this.store,{onPillSelected:({rawQuery:o,selectedPill:i,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:i,other_pills:r})}}),this.reEdit=new Ue({store:this.store,scheduleSetCursor:o=>this.scheduleSetCursor(o),fireTelemetry:(o,i)=>this.fireTelemetry(o,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Be(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Fe(this.store,()=>this.opts.optionOverrides,{onAnswer:o=>{o==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(o,i)=>{o==="pill"&&i.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Ae(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:o,signal:i,isCurrent:r})=>{this.productsController.run(o,i,r).catch(()=>{})},onAutoMatch:({active:o,matched:i,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:i.text,other_options:(o.options??[]).filter(s=>s.text!==i.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:o=>this.productsController.forResponse(o),consumerTick:(o,i)=>this.optionSource.tick(o,i)}),this.keyboardController=new Ne(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption:o=>this.selectOption(o),removeParamAtCaret:o=>this.removeParamAtCaret(o),startEditingParamAtCaret:o=>this.startEditingParamAtCaret(o),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((o,i)=>{o.text!==i.text&&this.emitter.emit("change",o.text),o.completedParams!==i.completedParams&&this.emitter.emit("paramsChange",o.completedParams),o.isFocused!==i.isFocused&&(o.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",o)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.subscribeSkeletonMirror(),this.unsubscribers.push(this.store.subscribe((o,i)=>{if(o.text===i.text&&o.completedParams===i.completedParams||o.identifiedParams.length===0)return;let{valid:r,invalid:s}=Ie(o.text,o.completedParams,o.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((o,i)=>{if(o.identifiedParams===i.identifiedParams)return;let r=o.editingIdentified;if(!r||o.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of o.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(o=>{let i=o.pendingRangeStart;!i||i.key===ge(o)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((o,i)=>{let r=o.pendingSpan;if(!r||o.text===i.text&&o.completedParams===i.completedParams&&o.identifiedParams===i.identifiedParams)return;let s=r.anchor;if(o.text!==i.text){let l=En(i.text,o.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}o.text.slice(s).trim().length===0||wn(o.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(ko(this.opts.styleRoot??Q(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({...Bo(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),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&&(zn(this.domRefs.input),qt(this.domRefs.dropdown)),this.dropdownRefs&&qt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let o of this.store.get().segments){let i=t;if(t+=o.value.length,o.type!=="text"&&e>i&&e<=t)return{kind:o.type,param:o.param,start:i,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(o=>o.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(o=>o.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:o}=this.store.get(),{start:i,end:r}=t;if(e===r){let{text:l,removed:c}=qe(o,i,r);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>i?Math.max(i,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let s=bt(o,e),a=o.slice(0,s)+o.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),L(t.input,e);else{let o=this.opts.setCursor;o&&this.boundary.runListener("setCursor",()=>o(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let o=t.identifiedParams.find(d=>d.id===e);if(!o)return!1;let i=U(o);if(!w(i))return!1;let r=ee(o.text),s=i==="date-range"||r?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+o.text.length;return this.store.set({editingIdentified:{id:e,type:o.type,anchor:l,tail:c,text:o.text,iso:r?r.start:lt(o),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){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 t=this.store.get();if(!w(t.activeFormatType)||!t.dateView)return;let o=it(t.dateView,e);this.store.set({dateViewMonth:{...o,key:ge(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),o=e.suggestions.filter(a=>a.type!=="placeholder");if(o.length===0)return;let i=o[0],r=o.slice(1),s=e.skippedParams.some(a=>a.type===i.type);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:i.type,suggestionPlaceholder:i.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 t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(o=>{this.boundary.runListener("subscribe",()=>e(o),t)})}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,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,o=this.opts.showProducts,i=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==i&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==o)&&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 t=this.store.get();if(t.activeFormatType==="date-range"){let i=N(e);if(i){let r=t.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:i,key:ge(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(pn(r,i));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.timers.clear(jt),this.reEdit.selectOption(e);return}let o=Vn(t,e);if(o){if(this.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:o.telemetry.selectedOption,other_options:w(t.activeFormatType)?[]:o.telemetry.otherOptions}),this.timers.clear(jt),this.store.set({...o.patch,...$e(t)}),this.startSelectionAnimationTimer(),this.timers.clear(Fo),o.remainingActionable>0){let i=o.consumedSuggestion;this.timers.schedule(Fo,()=>{this.store.get().suggestions.includes(i)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==i)}))},Ho)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Er,()=>this.store.set({inSelectionAnimation:!1}),Ho)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let o=this.resolveSource();No({source:o,sessionId:this.sessionId,type:e,queryData:t,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 ye(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={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:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Ao(this.container,t);let o=()=>{this.domRefs&&Kt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(o),this.subscribeViewportBreakpoint(o),Kt(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={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:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=To(this.container,t);let o=()=>{this.dropdownRefs&&Ut(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(o),this.subscribeViewportBreakpoint(o),Ut(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(We),o=()=>e();t.addEventListener("change",o),this.unsubscribers.push(()=>t.removeEventListener("change",o))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,t)=>{if(!e.skeletonOptions)return;if(!t.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!t.isLoading||e.isLoading)return;let o={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(o);return}this.timers.schedule(jt,()=>this.store.set(o),Ir)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Pr,()=>this.store.set({newParamId:null}),Tr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:i}=On(e,t.completedParams);i.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 t=F(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),o=vn(e.segments,t);e.text.slice(o).trim().length!==0&&this.store.set({pendingSpan:{anchor:o,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 t=e.caretOffset??e.editingAnchor,o=e.text.slice(e.editingAnchor,t);K(e.editingParam.options,o).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:o}=R(e.text,e.completedParams);this.fetchController.doFetch(t,o)}commitIdentifiedDate(e){let t=this.store.get(),o=t.editingIdentified;if(!o)return;if(t.text.slice(o.anchor,o.tail)!==o.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let i=t.text.slice(0,o.anchor),r=t.text.slice(o.tail),s=o.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=r.length===0||r[0]!==" "?`${s} `:s,c=i+l+r,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:o.type,text:s,value:e.value,kind:e.kind,suggestionType:o.type,suggestionPlaceholder:$(o.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(m=>m.id!==o.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(w(t.activeFormatType))return;let o=Ge({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});o&&this.store.set(o.patch)}};export{zt as AIAutocomplete,Xn as ATTRIBUTION_URL,ut as DATE_RANGE_META_END,ct as DATE_RANGE_META_START,po as DEFAULT_OPTION_COUNT_UNIT,ye as ModeController,We as OPTIONS_GRID_MOBILE_QUERY,Ft as OPTION_ENTER_DELAY_VAR,Wi as OPTION_ENTER_FADE_MS,Gi as OPTION_ENTER_RISE_MS,$i as OPTION_ENTER_RISE_PX,Bi as OPTION_ENTER_STAGGER_MS,Ci as PLACEHOLDER_FADE_OUT_MS,oe as PLACEHOLDER_LEAVING_ATTR,Oi as PLACEHOLDER_SWAP_GAP_MS,Ei as PLACEHOLDER_TYPE_MS,Ti as PLACEHOLDER_WORD_PAUSE_MS,Bn as PRODUCT_PATH_PREFIX,_i as PRODUCT_ROW_PX_PER_LINE,cn as RANGE_SEPARATOR,So as SCROLL_ARROW_ATTR,wo as SCROLL_ARROW_BOTTOM_VAR,yo as SCROLL_ARROW_CLASS,xo as SCROLL_ARROW_FADE_MS,Po as SCROLL_ARROW_LABEL,vo as SCROLL_ARROW_SCROLL_IDLE_MS,se as SCROLL_ARROW_VISIBLE_ATTR,fn as SKIPPED_PARAM_TEXT,Se as WEEKDAY_LABELS,it as addMonths,Mt as attachProductRowWheel,$t as attachScrollArrow,It as buildAttributionUrl,rt as buildDateOptions,R as buildQuery,j as buildSubmitResult,at as cellDay,N as cellIso,Gn as computeOptionsGridLayout,Qt as createStore,ht as cursorIsAtEnd,Lt as dateCellMarks,fe as dateSelectionFor,_e as extractPlainText,Z as formatAbsoluteDate,rn as formatDate,un as formatDateRange,he as formatOptionCount,_ as getCursorOffset,At as getFooterHint,$ as identifiedParamLabel,w as isCalendarFormat,Ct as isOptionsGridMobileViewport,k as isoDate,Tt as measureOptionsGrid,nt as monthLabel,Pt as needsOptionsGridMeasurement,qi as optionCountLabel,Ht as optionEnterDelayMs,Ui as optionHasImage,G as optionImageSrc,Wt as optionLabel,Bt as optionsEntranceDurationMs,wt as optionsGridTemplateColumns,xe as parseDate,q as parseLooseDate,ee as parseLooseDateRange,ft as plainTextLength,Et as planOptionsGrid,bt as previousGraphemeBoundary,Wn as productFromMatchedItem,kt as productInitial,so as productRowWheelTarget,xt as productsFromCustomFields,Vt as renderEditableContent,U as resolveFormatType,lt as resolveIdentifiedDate,Ot as sameOptionRows,be as sanitizeOptionIconSvg,gt as scrollCaretIntoView,st as selectedIsoFromText,de as selectedRangeFor,L as setCursorOffset,ue as toWireIdentifiedParams,Rt as visibleDateRange,pe as withSkippedParams};
2131
2177
  //# sourceMappingURL=index.mjs.map