@magicx-eng/ai-autocomplete-vanilla 0.32.0 → 0.32.1

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