@magicx-eng/ai-autocomplete-vanilla 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,93 +1,87 @@
1
- function Ve(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function W(n){let e=Ve(n);return e.length>0?e.join(" "):n}var U=["January","February","March","April","May","June","July","August","September","October","November","December"],de=["S","M","T","W","T","F","S"],Ft=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Ht="aiaDate",Bt="aiaDay",_t=n=>String(n).padStart(2,"0");function R(n){return`${n.getFullYear()}-${_t(n.getMonth()+1)}-${_t(n.getDate())}`}function Ke(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function ai(n){let e=Ke(n).getTime()-Ke(new Date).getTime();return Math.round(e/864e5)}function Wt(n){let e=ai(n);return e>=0&&e<7?Ft[n.getDay()]:Q(n)}function Q(n){return n.getFullYear()===new Date().getFullYear()?`${U[n.getMonth()]} ${n.getDate()}`:`${U[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ce(n){if(!n)return null;let e=Ft.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Ke(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=U.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let r=Number(t[2]),o=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(o,i,r);return s.getMonth()!==i||s.getDate()!==r?null:s}function Ue(n){return`${U[n.month]} ${n.year}`}function Qe(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Gt(n){return{year:n.getFullYear(),month:n.getMonth()}}function Ye(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Nt(){return{text:"",is_tappable:!1,kind:null}}function je(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let r=0;r<e;r++)i.push(Nt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Wt(o),is_tappable:!0,kind:null,metadata:{[Ht]:R(o),[Bt]:r}})}for(;i.length%de.length!==0;)i.push(Nt());return i}function ze(n){let e=ce(n);return e?R(e):null}function _(n){let e=n?.metadata?.[Ht];return typeof e=="string"?e:null}function Xe(n){let e=n?.metadata?.[Bt];return typeof e=="number"?e:null}function li(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function $t(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:U.findIndex(t=>t.toLowerCase().startsWith(e))}function di(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=r)return i;let o=new Date(t.getFullYear()+1,n,e);return o.getMonth()===n&&o.getDate()===e?o:null}function qt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function G(n,e={}){if(!n)return null;let t=e.today??new Date,i=li(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=qt(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?R(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=$t(o[1]);if(l>=0)return ue(l,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=$t(s[2]);if(l>=0)return ue(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?ue(c-1,l,a[3],t):c>12&&l<=12?ue(l-1,c,a[3],t):null}return null}function ue(n,e,t,i){if(t){if(t.length!==4)return null;let o=qt(Number(t),n,e);return o?R(o):null}let r=di(n,e,i);return r?R(r):null}function Je(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:G(n.text,e)}var Kt=" - ",et="aiaDateRangeStart",tt="aiaDateRangeEnd";function ee(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Ze=/^\d{4}-\d{2}-\d{2}$/;function Vt(n){if(!Ze.test(n))return null;let[e,t,i]=n.split("-").map(Number),r=new Date(e,t-1,i);return r.getMonth()===t-1&&r.getDate()===i?r:null}var ci=/\s+(?:to|through|thru|until|til|till)\s+/g,ui=/[-–—]/g;function pi(n){let e=[];for(let t of[ci,ui]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function Y(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[r,o]of pi(n.trim())){let s=G(r.trim(),e);if(!s)continue;let a=G(o.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function Ut(n){let e=Vt(n.start),t=Vt(n.end);return!e||!t?"":n.start===n.end?Q(e):`${Q(e)}${Kt}${Q(t)}`}function Qt(n,e){let t=ee(n,e);return{text:Ut(t),is_tappable:!0,kind:null,metadata:{[et]:t.start,[tt]:t.end}}}function te(n,e={}){let t=n?.metadata?.[et],i=n?.metadata?.[tt];return typeof t=="string"&&typeof i=="string"&&Ze.test(t)&&Ze.test(i)?ee(t,i):Y(n?.text,e)}function E(n){return n==="date"||n==="date-range"}var mi=new Set(["date","dates"]),fi=new Set(["range","ranges","span","period","window"]),Yt=3;function gi(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(Y(t.text)!==null?e.range+=1:G(t.text)!==null&&(e.single+=1));return e}function $(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=gi(n.options);if(t.single+t.range>=Yt&&t.range>t.single)return"date-range";let i=Ve(n.type);return i.some(r=>mi.has(r))?i.some(r=>fi.has(r))?"date-range":"date":t.single>=Yt?"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 hi="https://api.ai-autocomplete.com",me=`${hi}/api/suggest`,jt=new WeakMap;function ne(n){return n?.type==="accessToken"}function bi(n){if(!(!n||ne(n)))return n}function fe(n){let e=jt.get(n.getAccessToken);return e||(e=new pe(n),jt.set(n.getAccessToken,e)),e}function ge(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function he(n){let e=bi(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ie(n){return n.map(e=>({type:e.type,value:e.text}))}var zt="skipped";function re(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:zt,kind:null}));return i.length>0?[...n,...i]:n}var yi="0.22.0",Xt=!1;function Si(){return crypto.randomUUID()}function xi(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function vi(n,e,t,i,r,o,s,a){let l=e.find(d=>d.type==="contact"&&d.metadata?.contact_account_count)?.metadata?.contact_account_count,c=typeof l=="number"?l:void 0;return{data:{raw_query:n,completed_params:re(e.map(d=>xi(d,t)),s??[]),...r&&r.length>0&&{identified_params:ie(r)},...o&&o.length>0&&{recently_suggested:o},...c!=null&&{contact_account_count:c},...a!==void 0&&{additional_context:a}},meta:{request_id:Si(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:yi,session_id:i}}}async function Jt(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Zt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=vi(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=ge(i),a=i?.endpoint??me,l=JSON.stringify(o);if(ne(i)){let u=fe(i),m=await u.getToken(),g=await Jt(a,s,m,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await Jt(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=he(i);!c&&!Xt&&(Xt=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(s.Authorization=c);let d=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function O(n,e){let t=n,i={},r=[],o=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&o.some(b=>h<b.end&&h+a.text.length>b.start);)h=t.indexOf(a.text,h+1);return h},m=u(s);if(m===-1&&(m=u(0)),m!==-1){t=t.slice(0,m)+d+t.slice(m+a.text.length);let g=d.length-a.text.length;for(let h of o)h.start>=m+a.text.length&&(h.start+=g,h.end+=g);o.push({start:m,end:m+d.length}),s=m>=s?m+d.length:s+g}r.push({...a,placeholder:d})}return{rawQuery:t,completedParams:r}}function H(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function be(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function q(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function en(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function V(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function j(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function tn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function nn(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function rn(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function on(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function sn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function nt(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function an(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);for(;a!==-1&&e.some(l=>a<l.end&&a+s.text.length>l.start);)a=n.indexOf(s.text,a+1);if(a===-1){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function ln(n,e,t=[]){let i=nt(n,e).located,r=an(n,i,t).located,o=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...r.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),s=[],a=0;for(let c of o)c.start>a&&s.push({type:"text",value:n.slice(a,c.start)}),s.push(c.segment),a=c.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function dn(n,e){let{located:t,missing:i}=nt(n,e);return{valid:t.map(r=>r.param),invalid:i}}function ye(n,e,t){let i=nt(n,e).located,{located:r,missing:o}=an(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function Pi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Ei=100,wi=300,Ti=2,Se=class{constructor(e,t,i,r,o,s,a,l={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=s;this.getAdditionalContext=a;this.callbacks=l;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===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 Zt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let c=(l.data.input??[]).filter(y=>y.source==="identified").map(y=>({id:crypto.randomUUID(),type:y.type,text:y.text})),d=tn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],m=u[u.length-1],g=this.store.get().text,h,b;if(m?.state==="in_progress"){b=!0;let y=g.toLowerCase().lastIndexOf(m.text.toLowerCase());h=y!==-1?y:o}else b=!1,h=o;let p=d.filter(y=>y.type!=="placeholder")[0],f=null;if(p&&!E($(p))){let y=q(g,h,b),w=j(p.options,y);w&&(f={id:crypto.randomUUID(),placeholder:"",type:p.type,text:w.text,kind:w.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:w.metadata,icon:w.icon,icon_svg:w.icon_svg},d=d.filter(T=>T!==p),this.callbacks.onAutoMatch?.({active:p,matched:w,rawQuery:e}))}let S=l.data.custom_fields??null,x=this.callbacks.productsForResponse?.(S);this.store.set(y=>{let w=f?[...y.completedParams,f]:y.completedParams,T=ye(y.text,w,c).valid,N=new Set(s.skippedParams.map(C=>C.id)),F=new Set(y.skippedParams.filter(C=>!N.has(C.id)).map(C=>C.type));return{suggestions:F.size>0?d.filter(C=>C.type==="placeholder"||!F.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:b,identifiedParams:T,customFields:S,...x!==void 0?{products:x}:{},...f?{completedParams:w}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=Pi(s);r===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(r===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(Ti)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ei),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),wi)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let r=this.callbacks.consumerTick?.(i,e)??"no";if(r==="asked")return!0;if(r==="owns")return!1;let o=i.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),s=H(i.text,i.filterBase,o),a=q(i.text,s,i.filterInProgress),c=i.suggestions.filter(x=>x.type!=="placeholder")[0],d=E(i.activeFormatType),m=(c&&!d?V(c.options,a):[]).filter(x=>x.is_tappable),g=c&&!d?j(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!g&&h||be(i.text,i.completedParams.length,o))return!1;let{rawQuery:b,completedParams:v}=O(i.text,i.completedParams),p=b.length<i.lastRawQuery.length,f=Math.abs(b.length-i.lastRawQuery.length),S=t&&b!==i.lastRawQuery;return p||f>=e||S?(this.doFetch(b,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ci(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function xe(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Ci(e)?e:n.ownerDocument??n}function I(n){return n.ownerDocument??n}function L(n){let t=xe(n).getSelection?.();return t||(I(n).getSelection?.()??null)}function ve(n,e){let t=n?xe(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Pe=2,Ai="magicx-aia";function cn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Oi(n){let e=I(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let r=i.scrollWidth>i.clientWidth,o=i.scrollHeight>i.clientHeight;if(r||o){let s=t.getComputedStyle(i);if(r&&cn(s.overflowX)||o&&cn(s.overflowY))return i}if(i.classList.contains(Ai))return null;i=i.parentElement}return null}function it(n){let e=L(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=Oi(n);if(!i||typeof t.getBoundingClientRect!="function")return;let r=t.getBoundingClientRect();if(r.height===0)return;let o=i.getBoundingClientRect();if(i.scrollWidth>i.clientWidth){let s=o.left+i.clientLeft,a=s+i.clientWidth;r.right>a?i.scrollLeft+=r.right-a+Pe:r.left<s&&(i.scrollLeft-=s-r.left+Pe)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+Pe:r.top<s&&(i.scrollTop-=s-r.top+Pe)}}var mn='[contenteditable="false"]',Ii="strong[data-param-id]",z;function Di(){if(z!==void 0)return z;let n=globalThis.Intl.Segmenter;if(!n)return z=null,null;try{z=new n(void 0,{granularity:"grapheme"})}catch{z=null}return z??null}function Ee(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(mn))return!0;t=t.parentNode}return!1}function we(n){return I(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Ee(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Te(n){let e=we(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function rt(n){let e=we(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function k(n){let e=L(n);if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(Ee(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=fn(r.childNodes[s],n);return o+un(r,n)}return t.nodeType!==Node.TEXT_NODE||Ee(t,n)?null:un(t,n)+i}function fn(n,e){if(n.nodeType===Node.TEXT_NODE)return Ee(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(mn))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=fn(r,e);return i}function un(n,e){let t=we(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function D(n,e){let t=I(n),i=L(n);if(!i)return;let r=Math.max(0,Math.min(e,rt(n))),o=we(n),s=0,a=null,l=0,c=o.nextNode(),d=null;for(;c;){let m=c.data.length;if(r<s+m){a=c,l=r-s;break}if(r===s+m){let g=o.nextNode();g?(a=g,l=0):(a=c,l=m);break}s+=m,d=c,c=o.nextNode()}let u=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?u.setStartBefore(m):l===a.data.length?u.setStartAfter(m):u.setStart(a,l):u.setStart(a,l)}else d?u.setStart(d,d.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u),Ri(n,i,u,r),it(n)}function pn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Ii)??null;return i&&e.contains(i)?i:null}function Ri(n,e,t,i){let r=pn(e.anchorNode,n);if(r&&r!==pn(t.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${i}:${r.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function gn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=k(n);return i!==null&&t===`${i}:${e}`}function ot(n){let e=k(n);return e==null?!1:e>=rt(n)}function st(n,e){if(e<=0)return 0;let t=Di();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function K(n,e,t=[],i={}){let{rawQuery:r,completedParams:o}=O(n,e);return{query:n.trim(),raw_query:r,completed_params:re(o,t),identified_params:ie(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function at(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?ot(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?k(n):null}var Ce=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(o),a=r(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=at(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(E(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(t.activeDropdownIndex),g=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let m=at(e.target,t),g=!!t.editingParam;if(!m&&!g)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),E(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),D(u,m);break}at(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),D(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=lt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,o):a&&a(K(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),m;if(u<0)m=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;m=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[m]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),D(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}dateEntryIndex(e,t){let i=R(new Date),r=e.filteredOptions.findIndex(s=>_(s)===i);if(r>=0)return r;let o=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?o[o.length-1]:o[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((o,s)=>o.is_tappable?s:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(e){let t=ve(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=ve(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;r;){let o=getComputedStyle(r).gridTemplateColumns;if(o&&o!=="none"){let s=o.split(" ").filter(Boolean).length;if(s>0)return s}if(r===t)break;r=r.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,r){let o=ve(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Ae=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let r=this.current;if(r&&r.key===i.key){if(r.query===i.query)return"owns";let o=Math.abs(i.query.length-r.query.length),s=i.query.length<r.query.length;if(t>1&&!s&&o<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(E(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let r=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:r};let o;try{o=t(e.query,r.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(o)){this.commit(e,o,i);return}this.setSearch(e,"loading"),this.await(e,o,r.signal,i)}async await(e,t,i,r){let o;try{let s=await t;if(i.aborted||r!==this.version)return;o=Array.isArray(s)?s:[]}catch(s){if(i.aborted||r!==this.version||Mi(s))return;this.logOnce(s),o=[]}this.commit(e,o,r)}commit(e,t,i){if(i!==this.version)return;let r=this.resolveTarget(this.store.get());if(!r||r.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let o={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:t}:s.editingParam,optionSearch:o}));else{let s={...e.suggestion,options:t};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:o}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Mi(n){return n instanceof Error&&n.name==="AbortError"}var Oe=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.filter((c,d)=>d!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=O(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:r.text,otherPills:o.map(d=>d.text)})}let a=[...s,r,...o],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var hn="/products/";function bn(n){return{id:n.source_id,title:n.title,...n.handle&&{url:`${hn}${encodeURIComponent(n.handle)}`},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function dt(n){return(n?.items.matched??[]).map(bn)}var Ie=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return dt(e)}async run(e,t,i){if(!this.isEnabled())return;let r=this.getConfig();if(!r)return;if(e.trim().length===0){this.clear(i);return}let o=()=>t.aborted||!i()||!this.owns(r);try{let s=await r.fetch(e,t);if(o())return;let a=r.transform(s),l=Array.isArray(a)?a:[],c=r.limit!=null?l.slice(0,r.limit):l;if(o())return;this.commit(c)}catch(s){if(t.aborted||Li(s)||(this.logOnce(s),o()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function Li(n){return n instanceof Error&&n.name==="AbortError"}var De="(max-width: 768px)";var ki="var(--aia-option-row-height, 37px)",_i="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function yn(n,e){return e?ct(1,Math.min(n,5)):ct(1,Math.min(n,4))}function ct(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${ki} + ${_i})`}}function pt(n,e){return!e&&n>=5}function mt(n,e,t,i){if(!(!e&&n>=5&&Ni(t,i))){let s=yn(n,e);return{...s,template:ut(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let o=6;return{...ct(2,3),template:ut(2),scrollHintIndices:n>o?[o-2,o-1]:[]}}function Ni(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function ft(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let r=getComputedStyle(n),o=n.clientWidth-(Number.parseFloat(r.paddingLeft)||0)-(Number.parseFloat(r.paddingRight)||0)-(Number.parseFloat(r.columnGap)||0);return{rowWidths:i,gridWidth:o}}function ut(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function gt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(De).matches}function Sn(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&c}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function oe(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function xn(n){if(!n)return Qe();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Fi(n){let e=ce(n);return e?Gt(e):Qe()}function vn(n,e){let t=ln(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(P=>P.type!=="placeholder"),r=i[0],o=n.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" "),s=H(n.text,Math.min(n.filterBase,n.text.length),o),l=s===0&&be(n.text,n.completedParams.length,o)?"":q(n.text,s,n.filterInProgress),c=r?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,m,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let P=n.editingParam.id,M=n.completedParams.some(si=>si.id===P),Z=n.caretOffset??n.editingAnchor,kt=M?"":n.text.slice(n.editingAnchor,Z);m=kt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=V(n.editingParam.options,kt)}else m=l.trim(),g=c,h=r?.type,u=V(c,l);let b=n.optionSearch,v=b!=null&&h!=null&&b.type===h;v&&b.status==="done"&&b.query===m&&(u=g);let p=v&&b.status==="loading",f=e.showNonTappableOptions===!1;f&&(u=u.filter(P=>P.is_tappable));let S=n.editingIdentified,x=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,y=S?S.format:$(x),w=d&&E(y)?te(n.editingParam):null;w&&(y="date-range");let T=null,N=null;if(E(y)){let P=oe({...n,actionableSuggestions:i}),M=n.dateViewMonth;T=M&&M.key===P?{year:M.year,month:M.month}:S?xn(S.iso):w?xn(w.start):Fi(n.editingParam?.text),u=je(T);let Z=n.pendingRangeStart;y==="date-range"&&Z&&Z.key===P&&(N=Z.iso)}let F=P=>f?P.is_tappable:!0,A;if(d){let P=n.editingParam?.options??[];A=n.editingParam!=null&&P.filter(F).length===0}else A=r!=null&&c.filter(F).length===0;let C=Sn({inEditMode:d||S!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:A,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),qe=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:y,dateView:T,dateRangeStart:N,placeholderText:o,optionQuery:m,isSearchingOptions:p,isDropdownOpen:C,isActivePillSelected:qe}}function Re(n){return n.mode==="fresh"?Hi(n):Bi(n)}function Hi(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(x=>x.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),c=H(e,r,l),d=q(e,c,o),u=j(a.options,d);if(!u)return null;let m=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(m),h=g>=0?g:Math.max(0,e.length-u.text.length),b=h+u.text.length,v=e.slice(h,b),f=b<e.length&&e[b]===" "?b+1:b,S={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg};return{patch:{text:e,completedParams:[...t,S],suggestions:i.filter(x=>x!==a),filterBase:f,newParamId:S.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function Bi(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(S=>S.id===i.id))return null;let s=e.slice(r,o),a=j(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=r+Math.max(0,c),u=d+a.text.length,m=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg},v=t.length,p=0;for(let S=0;S<t.length;S++){let x=e.indexOf(t[S].text,p);if(x!==-1){if(x>=g){v=S;break}p=x+t[S].text.length}}let f=[...t];return f.splice(v,0,b),{patch:{text:e,completedParams:f,newParamId:b.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Me(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var Le=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?Me(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},a=r+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let s=t.text.slice(0,r),a=t.text.slice(o),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,m=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=t.completedParams.findIndex(p=>p.id===i.id),b=t.completedParams.filter(p=>p.id!==i.id),v=h>=0?Math.min(h,b.length):b.length;b.splice(v,0,g),this.deps.store.set({text:u,completedParams:b,newParamId:g.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Re({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Wi=33,Gi=70,$i=120,qi=50,X="data-aia-placeholder-leaving",J=new WeakMap;function ke(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Vi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function En(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function wn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(En(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>wn(n,e),33+i)}function Pn(n,e){En(n,e,0),e.timer=setTimeout(()=>wn(n,e),33)}function Tn(n,e){let t=J.get(n);if(e===""){t&&(ke(t),J.delete(n)),n.removeAttribute(X),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Vi(n)){t&&ke(t),n.removeAttribute(X),J.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},r=t&&t.shown>0?t:null;if(t&&ke(t),J.set(n,i),r){n.setAttribute(X,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(X),n.isConnected&&Pn(n,i)},170);return}n.removeAttribute(X),Pn(n,i)}function Cn(n){let e=J.get(n);e&&(ke(e),J.delete(n))}var An="https://ai-autocomplete.com";function ht(n=An){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function bt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ki={selectedIso:null,selectedRange:null,rangeStart:null};function se(n){if(!E(n.activeFormatType))return Ki;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:r}=e;return{selectedIso:r?null:i,selectedRange:i&&r?ee(i,r):null,rangeStart:n.dateRangeStart}}let t=te(n.editingParam);return{selectedIso:t?null:ze(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function yt(n){return n.pendingStart?ee(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function St(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,r=n===t||i!=null&&(n===i.start||n===i.end),o=i!=null&&n>i.start&&n<i.end;return{selected:r,inRange:o}}var On="data-aia-key";function B(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(On);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);r.add(l);let c=i.get(l);c||(c=t.create(a,s),c.setAttribute(On,l)),t.update?.(c,a,s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null),o.push(c)}for(let[s,a]of i)r.has(s)||a.remove();return o}function Dn(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=Yi(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=Ue(r));let c=a.querySelector("[data-aia-date-prev]"),d=a.querySelector("[data-aia-date-next]");c&&(c.onclick=()=>s.onPreviousMonth()),d&&(d.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&Ui(u,e,t,i,o,s)}function Ui(n,e,t,i,r,o){let s=R(new Date),a=yt({pendingStart:r.rangeStart,highlightedIso:_(e[t]),selected:r.selectedRange});B(n,e,{keyOf:(l,c)=>_(l)??`pad-${c}`,create:l=>Qi(l),update:(l,c,d)=>{let u=_(c),m=St(u,{selectedIso:r.selectedIso,range:a}),g=d===t&&c.is_tappable;l.id=`${i}-option-${d}`,l.dataset.aiaIndex=String(d),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<s),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===s),l.classList.toggle("magicx-aia-date-cell--selected",m.selected),l.classList.toggle("magicx-aia-date-cell--in-range",m.inRange),c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(c),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let h=Number.parseInt(l.dataset.aiaIndex??"-1",10);h>=0&&o.onHighlight(h)}):(l.onclick=null,l.onmouseenter=null)}})}function Qi(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=Xe(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function Yi(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(In("prev","Previous month","\u2039"),t,In("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of de){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=o,i.appendChild(s)}let r=document.createElement("div");return r.className="magicx-aia-datepicker-grid",r.setAttribute("data-aia-date-grid",""),n.append(e,i,r),n}function In(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",r=>r.preventDefault()),i}var Rn=[125,69];function Mn(n,e){return e?1:n===0?.7:n===1?.4:.2}function _e(n,e,t,i,r=!1,o=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Rn.length;l++){let c=Rn[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(Mn(l,!1)),a.appendChild(d)}return}o?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();B(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.addEventListener("mousedown",d=>d.preventDefault()),c},update:(l,c,d)=>{let u=l,m=s&&d===t&&!o,g=["magicx-aia-pill"];r&&g.push("magicx-aia-pill--rounded"),o&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(Mn(d,m)),o?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(d))}})}function xt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ji="Products";function Ln(n,e,t,i,r){let o=n.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let a=document.createElement("div");a.className="magicx-aia-products-label",a.id=`${t}-products-label`,a.textContent=ji;let l=document.createElement("div");l.className="magicx-aia-products-row",l.setAttribute("data-aia-products-row",""),o.append(a,l),n.appendChild(o)}let s=o.querySelector(".magicx-aia-products-row");s&&B(s,e,{keyOf:a=>zi(a),create:a=>Xi(a,i,r),update:(a,l,c)=>{a.id=`${t}-product-${c}`,a.dataset.aiaIndex=String(c)}})}function vt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function zi(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Xi(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),n.url&&(i.href=n.url),i.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",r.appendChild(a)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,o.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,o.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,o.appendChild(a)}return i.appendChild(o),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var Ji=80,Zi=150,er=280,tr=16,Pt="--aia-option-enter-delay";function Et(n,e,t,i="below"){let r=Math.max(1,Math.floor(e)),o=Math.floor(Math.max(0,n)/r);if(i!=="above")return o*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/r));return Math.max(0,s-1-o)*80}function wt(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}var kn="http://www.w3.org/2000/svg",nr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function ir(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}function _n(n){for(let e of Array.from(n.attributes))ir(e.name,e.value)&&n.removeAttribute(e.name);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!nr.has(t.localName)||t.namespaceURI!==kn?t.remove():_n(t)}else e.remove()}function ae(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==kn||e.getElementsByTagName("parsererror").length>0?null:(_n(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function Tt(n){return n.icon&&!n.icon_svg?`${n.icon} ${n.text}`:n.text}function rr(n,e,t){let i=gt(),r=!t&&pt(e,i)?ft(n):null,o=mt(e,i,r?.rowWidths??null,r?.gridWidth??null);return n.style.gridTemplateColumns=o.template,n.style.setProperty("--aia-grid-max-height",o.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&o.scrollHintIndices.includes(a))}),o.cols}function Nn(n,e,t,i,r,o,s,a="",l="below",c=!0){let d=n.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),n.appendChild(d));let u=d.dataset.aiaGroup!==a;d.dataset.aiaGroup=a,or(d,e,t,i,r,o,s,c);let m=rr(d,e.length,s);sr(d,e.length,m,s,l),u&&(d.scrollTop=0)}function or(n,e,t,i,r,o,s,a){let l=s?"1":"0",c=n.dataset.aiaGroup??"",d=a?u=>u.icon??u.icon_svg??"":()=>"";B(n,e,{keyOf:u=>`${u.text}\0${d(u)}\0${l}\0${c}`,create:(u,m)=>{let g=ar(u,s,a);return s||(g.dataset.aiaEntering=""),g},update:(u,m,g)=>{let h=g===t&&!s;u.id=`${o}-option-${g}`,u.dataset.aiaIndex=String(g),u.setAttribute("aria-selected",String(h)),u.classList.toggle("magicx-aia-option--highlighted",h),!s&&m.is_tappable?(u.onclick=()=>{u.classList.add("magicx-aia-option--pressed"),i(m),setTimeout(()=>u.classList.remove("magicx-aia-option--pressed"),170)},u.onmouseenter=()=>{let b=Number.parseInt(u.dataset.aiaIndex??"-1",10);b>=0&&r(b)}):(u.onclick=null,u.onmouseenter=null)}})}function sr(n,e,t,i,r){for(let o of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(o.dataset.aiaIndex??"-1",10);s>=0&&o.style.setProperty(Pt,`${Et(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function ar(n,e,t){let i=document.createElement("div");i.setAttribute("role","option"),i.setAttribute("data-aia-option",""),e&&i.setAttribute("data-aia-loading",""),i.tabIndex=e||!n.is_tappable?-1:0;let r=["magicx-aia-option"];n.is_tappable?r.push("magicx-aia-option--tappable"):r.push("magicx-aia-option--non-tappable"),i.className=r.join(" ");let o=document.createElement("span");o.className="magicx-aia-option-content";let s=t&&n.icon_svg?ae(n.icon_svg):null;if(s){let l=document.createElement("span");l.className="magicx-aia-option-icon",l.setAttribute("aria-hidden","true"),l.innerHTML=s,o.appendChild(l),n.icon&&(i.dataset.aiaIcon=n.icon)}let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=Tt(n),o.appendChild(a),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,o.appendChild(l)}return i.appendChild(o),i}var Fn="magicx-aia-scroll-arrow",Hn="data-aia-scroll-arrow",Ne="data-aia-visible",lr=1e3,Bn=160,Wn="--aia-scroll-arrow-bottom",Gn="Scroll down for more options",dr=4,cr=8,ur=240;function pr(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||qn(n)){n.scrollTop=r+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/ur),u=1-(1-d)*(1-d);n.scrollTop=r+e*u,d<1?o.call(t,c):i()};o.call(t,c)}function mr(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function $n(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Fn,e.setAttribute(Hn,""),e.setAttribute("aria-label",Gn),e.setAttribute("aria-hidden","true"),e.appendChild(mr(n)),e}function fr(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function qn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ct({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),r=!1,o=null,s=null,a=null,l=v=>{v?(t.setAttribute(Ne,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(Ne),t.setAttribute("aria-hidden","true"))},c=()=>{let v=0,p=e;for(;p&&p!==n;)v+=p.offsetTop,p=p.offsetParent instanceof HTMLElement?p.offsetParent:null;let f=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0,S=n.clientHeight-(v+e.offsetHeight)+(f>0?0:cr);t.style.setProperty(Wn,`${Math.max(0,Math.round(S))}px`)},d=()=>{if(r||s!==null||a!==null)return;let v=e.querySelector("[data-aia-option][data-aia-loading]")!==null,p=e.scrollHeight-e.clientHeight-e.scrollTop;l(!v&&p>dr)},u=()=>{if(r)return;c();let v=e.getAttribute("data-aia-group")??"";if(v!==o){o=v,l(!1),s!==null&&clearTimeout(s);let p=e.querySelectorAll("[data-aia-option]").length,f=qn(e)?0:wt(p,fr(e));s=setTimeout(()=>{s=null,d()},f);return}d()},m=()=>{r||s!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,d()},Bn))};e.addEventListener("scroll",m,{passive:!0});let g=v=>v.preventDefault(),h=()=>{let v=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,p=Math.max(1,e.clientHeight-v);pr(e,p,i,m)};t.addEventListener("mousedown",g),t.addEventListener("click",h);let b=null;return i&&typeof i.ResizeObserver=="function"&&(b=new i.ResizeObserver(()=>{c(),d()}),b.observe(e)),u(),{update:u,destroy(){r||(r=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",m),t.removeEventListener("mousedown",g),t.removeEventListener("click",h),b?.disconnect(),t.removeAttribute(Ne),t.setAttribute("aria-hidden","true"))}}}var gr=[159,119,164];function He(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}var Fe=new WeakMap;function hr(n,e){let t=Fe.get(n);if(t||(t={button:$n(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Fe.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Ct({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function At(n){let e=Fe.get(n);e&&(e.controller?.destroy(),Fe.delete(n))}function Be(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:m}=e,g=s.length>0,h=a&&g,b=t.length>0,v=e.products.length>0,p=r&&(b||h||o||v);if(p?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!p){vt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let S=e.showSkipButton&&g&&!e.isInputEmpty,x=h||o&&a||S,y=f.querySelector(".magicx-aia-pill-bar");if(x){y||(y=document.createElement("div"),y.className="magicx-aia-pill-bar aia-cluster",y.setAttribute("data-nowrap",""),y.setAttribute("data-aia-pillbar",""),f.insertBefore(y,f.firstChild));let P=y.querySelector(".magicx-aia-pill-scroll");P||(P=document.createElement("span"),P.className="magicx-aia-pill-scroll",P.setAttribute("data-aia-pill-scroll",""),y.insertBefore(P,y.firstChild)),_e(P,a?s:[],0,u,!0,o&&a,l),yr(y,S,o||e.skipDisabled,s[0],m)}else y&&y.remove();let w=e.suggestions[0],T=w?`${w.type} ${w.text}`:"",N=E(e.formatType),F=N&&!o;Nn(f,N?[]:t,i,c,d,e.listboxId,o,T,e.optionsPosition??"below",e.showOptionIcons??!0),hr(n,f.querySelector(".aia-grid")),Dn(f,F?t:[],i,e.listboxId,F?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let A=f.querySelector(".magicx-aia-skeleton-bars");if(o&&(!b||N)){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let P of gr){let M=document.createElement("span");M.className="magicx-aia-skeleton-bar",M.style.width=`${P}px`,A.appendChild(M)}f.appendChild(A)}}else A&&A.remove();Ln(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),vt(n,!0);let C=f.querySelector(".magicx-aia-footer")??xr(),qe=i>=0&&!!t[i]?.is_tappable;Sr(C,bt(qe,e.isInputEmpty)),C.isConnected||f.appendChild(C),br(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function br(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function yr(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",s=>s.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Sr(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function xr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ht(),o.target="_blank",o.rel="noopener noreferrer",o.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",o.append(s,a),e.append(t,o),n.append(e),n}function Vn(n,e){let t=He(e.listboxId);return n.appendChild(t),{dropdown:t}}function Ot(n,e,t){let i=se(e);Be(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:W(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:r=>t.store.set({activeDropdownIndex:r}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:r=>t.store.set({isFocused:r})})}var vr=6,Pr=.3;function Kn(n){return n<=0?"0px":`${(-Math.min(Pr,2*vr/n)).toFixed(3)}px`}function It(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=n.showChipIcons??!0,l=t.length===0;e.dataset.aiaEmpty=l?"true":"false",Tn(e,l?o:"");let c=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}`:`${p.type}:${p.value}`).join("\0"),d=e.dataset.segKey??"",u=e.dataset.newParamId??"",m=e.dataset.editingParamId??"";if(c===d&&(i??"")===u&&(r??"")===m)return;let g=s?k(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=I(e),b=h.createDocumentFragment(),v=0;for(let p of t)if(v+=p.value.length,p.type==="completed"){let f=h.createElement("strong");f.dataset.seg="completed",f.dataset.paramId=p.param.id;let S=p.param.id===i,x=p.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];S&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&y.push("magicx-aia-segment--editing"),f.className=y.join(" "),f.style.letterSpacing=Kn(p.value.length);let w=a&&p.param.icon_svg?ae(p.param.icon_svg):null;if(w){let T=h.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=w,f.appendChild(T),p.param.icon&&(f.dataset.aiaIcon=p.param.icon)}f.appendChild(h.createTextNode(p.value)),b.appendChild(f)}else if(p.type==="identified"){let f=h.createElement("strong");f.dataset.seg="identified",f.dataset.paramId=p.param.id;let S=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===r&&S.push("magicx-aia-segment--editing"),f.className=S.join(" "),f.style.letterSpacing=Kn(p.value.length),f.textContent=p.value,b.appendChild(f)}else b.appendChild(h.createTextNode(p.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(v),g!=null&&D(e,Math.max(0,Math.min(g,v)))}var Er='<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 Un(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=Er,n}function wr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Qn(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Yn(n,e){let{listboxId:t}=e,i=He(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",wr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=Un(),r.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),r.appendChild(c));let d=new AbortController,{signal:u}=d,m=!1,g=0,h=()=>{let p=Te(s),S=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(S)},b=()=>{let p=L(s);if(!p||p.rangeCount===0)return null;let f=p.anchorNode;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(r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(g=performance.now(),h(),e.handleCaretAfterInput(k(s)))},{signal:u}),I(s).addEventListener("selectionchange",()=>{let p=L(s);if(!p||p.rangeCount===0||!s.contains(p.anchorNode))return;let f=p.isCollapsed?b():null,S=e.store.get(),x=S.editingParam?.id??S.editingIdentified?.id??null;if(f&&f!==x){e.startEditingParam(f);return}performance.now()-g<50||e.handleCaretMove(k(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",p=>{let f=p,S=f.inputType;if(S==="insertParagraph"||S==="insertLineBreak"||S==="insertFromDrop"){p.preventDefault();return}if(S.startsWith("insert")||S.startsWith("delete")){let x=S.startsWith("delete")?"":f.data??"";e.replaceEditingRange(x)&&p.preventDefault()}},{signal:u}),s.addEventListener("paste",p=>{p.preventDefault();let f=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let S=I(s),x=L(s);if(!x||x.rangeCount===0)return;let y=x.getRangeAt(0);if(!s.contains(y.startContainer))return;y.deleteContents();let w=S.createTextNode(f);y.insertNode(w),y.setStartAfter(w),y.collapse(!0),x.removeAllRanges(),x.addRange(y),h()},{signal:u}),s.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",p=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit(K(f.text,f.completedParams,f.skippedParams,{identifiedParams:f.identifiedParams,isReady:f.isReady,customFields:f.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let p=I(s),f=L(s),S=f&&f.rangeCount>0&&s.contains(f.anchorNode);if(f&&!S){let x=p.createRange();x.selectNodeContents(s),x.collapse(!0),f.removeAllRanges(),f.addRange(x)}}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>Qn(s,a));p.observe(s),d.signal.addEventListener("abort",()=>p.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function Dt(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let p=!!e.text||e.completedParams.length>0;s.disabled=!p}let m=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==m;if(It({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0}),a==="inline"){let p=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;p||e.actionableSuggestions.length>0?_e(r,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):xt(r)}else xt(r);Qn(i,r),g?(i.focus(),D(i,e.caretOffset??e.text.length)):e.isFocused&&Te(i)!==e.text&&D(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:W(e.editingIdentified.type),required:!0,options:[]}:null,b=h??e.actionableSuggestions[0],v=se(e);Be(o,{suggestions:b?[{...b,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:p=>d.set({activeDropdownIndex:p}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:p=>d.set({isFocused:p})})}function jn(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=en(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",c=`${r}${l?" ":""}${e.text} `,d=(o||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(b=>b.text!==e.text).map(b=>b.text)},consumedSuggestion:t,remainingActionable:h}}function Rt(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!r){r=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let m of t)m(d,u)}}catch(l){throw i.length=0,l}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function zn(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let l={...a,...r(a)},c={...s,...r(s)};o(c,l)})}}var Mt=new WeakSet,Xn=new WeakMap;function Zn(n){return n.nodeType===Node.DOCUMENT_NODE}function Tr(n){return Zn(n)?n:n.ownerDocument}function Cr(n){let e=Xn.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(ti),Xn.set(n,i),i)}catch{return null}}function Jn(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ti,e.appendChild(t)}function ei(n){if(typeof document>"u")return;let e=n??document;if(Mt.has(e))return;let t=Tr(e);if(Zn(e)){let o=e.head??e.documentElement;if(!o)return;Jn(t,o),Mt.add(e);return}let i=Cr(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):Jn(t,e),Mt.add(e)}var ti=`@layer layout {
2
- .aia-stack {
3
- display: flex;
4
- flex-direction: column;
5
- gap: var(--aia-stack-space, 0.5rem);
6
- }
7
- .aia-stack[data-align="start"] {
8
- align-items: start;
9
- }
10
- .aia-stack[data-align="center"] {
11
- align-items: center;
12
- }
13
- .aia-stack[data-align="end"] {
14
- align-items: end;
15
- }
16
- /* data-align="stretch" is the flex default \u2014 no rule needed. */
1
+ function Ve(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function W(n){let e=Ve(n);return e.length>0?e.join(" "):n}var U=["January","February","March","April","May","June","July","August","September","October","November","December"],de=["S","M","T","W","T","F","S"],Ft=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Ht="aiaDate",Bt="aiaDay",_t=n=>String(n).padStart(2,"0");function R(n){return`${n.getFullYear()}-${_t(n.getMonth()+1)}-${_t(n.getDate())}`}function Ke(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function ai(n){let e=Ke(n).getTime()-Ke(new Date).getTime();return Math.round(e/864e5)}function Wt(n){let e=ai(n);return e>=0&&e<7?Ft[n.getDay()]:Q(n)}function Q(n){return n.getFullYear()===new Date().getFullYear()?`${U[n.getMonth()]} ${n.getDate()}`:`${U[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ce(n){if(!n)return null;let e=Ft.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Ke(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=U.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let r=Number(t[2]),o=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(o,i,r);return s.getMonth()!==i||s.getDate()!==r?null:s}function Ue(n){return`${U[n.month]} ${n.year}`}function Qe(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Gt(n){return{year:n.getFullYear(),month:n.getMonth()}}function Ye(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Nt(){return{text:"",is_tappable:!1,kind:null}}function je(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let r=0;r<e;r++)i.push(Nt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Wt(o),is_tappable:!0,kind:null,metadata:{[Ht]:R(o),[Bt]:r}})}for(;i.length%de.length!==0;)i.push(Nt());return i}function ze(n){let e=ce(n);return e?R(e):null}function _(n){let e=n?.metadata?.[Ht];return typeof e=="string"?e:null}function Xe(n){let e=n?.metadata?.[Bt];return typeof e=="number"?e:null}function li(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function $t(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:U.findIndex(t=>t.toLowerCase().startsWith(e))}function di(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=r)return i;let o=new Date(t.getFullYear()+1,n,e);return o.getMonth()===n&&o.getDate()===e?o:null}function qt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function G(n,e={}){if(!n)return null;let t=e.today??new Date,i=li(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=qt(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?R(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=$t(o[1]);if(l>=0)return ue(l,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=$t(s[2]);if(l>=0)return ue(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?ue(c-1,l,a[3],t):c>12&&l<=12?ue(l-1,c,a[3],t):null}return null}function ue(n,e,t,i){if(t){if(t.length!==4)return null;let o=qt(Number(t),n,e);return o?R(o):null}let r=di(n,e,i);return r?R(r):null}function Je(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:G(n.text,e)}var Kt=" - ",et="aiaDateRangeStart",tt="aiaDateRangeEnd";function ee(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Ze=/^\d{4}-\d{2}-\d{2}$/;function Vt(n){if(!Ze.test(n))return null;let[e,t,i]=n.split("-").map(Number),r=new Date(e,t-1,i);return r.getMonth()===t-1&&r.getDate()===i?r:null}var ci=/\s+(?:to|through|thru|until|til|till)\s+/g,ui=/[-–—]/g;function pi(n){let e=[];for(let t of[ci,ui]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function Y(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[r,o]of pi(n.trim())){let s=G(r.trim(),e);if(!s)continue;let a=G(o.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function Ut(n){let e=Vt(n.start),t=Vt(n.end);return!e||!t?"":n.start===n.end?Q(e):`${Q(e)}${Kt}${Q(t)}`}function Qt(n,e){let t=ee(n,e);return{text:Ut(t),is_tappable:!0,kind:null,metadata:{[et]:t.start,[tt]:t.end}}}function te(n,e={}){let t=n?.metadata?.[et],i=n?.metadata?.[tt];return typeof t=="string"&&typeof i=="string"&&Ze.test(t)&&Ze.test(i)?ee(t,i):Y(n?.text,e)}function E(n){return n==="date"||n==="date-range"}var mi=new Set(["date","dates"]),fi=new Set(["range","ranges","span","period","window"]),Yt=3;function gi(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(Y(t.text)!==null?e.range+=1:G(t.text)!==null&&(e.single+=1));return e}function $(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=gi(n.options);if(t.single+t.range>=Yt&&t.range>t.single)return"date-range";let i=Ve(n.type);return i.some(r=>mi.has(r))?i.some(r=>fi.has(r))?"date-range":"date":t.single>=Yt?"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 hi="https://api.ai-autocomplete.com",me=`${hi}/api/suggest`,jt=new WeakMap;function ne(n){return n?.type==="accessToken"}function bi(n){if(!(!n||ne(n)))return n}function fe(n){let e=jt.get(n.getAccessToken);return e||(e=new pe(n),jt.set(n.getAccessToken,e)),e}function ge(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function he(n){let e=bi(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ie(n){return n.map(e=>({type:e.type,value:e.text}))}var zt="skipped";function re(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:zt,kind:null}));return i.length>0?[...n,...i]:n}var yi="0.23.0",Xt=!1;function Si(){return crypto.randomUUID()}function xi(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function vi(n,e,t,i,r,o,s,a){let l=e.find(d=>d.type==="contact"&&d.metadata?.contact_account_count)?.metadata?.contact_account_count,c=typeof l=="number"?l:void 0;return{data:{raw_query:n,completed_params:re(e.map(d=>xi(d,t)),s??[]),...r&&r.length>0&&{identified_params:ie(r)},...o&&o.length>0&&{recently_suggested:o},...c!=null&&{contact_account_count:c},...a!==void 0&&{additional_context:a}},meta:{request_id:Si(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:yi,session_id:i}}}async function Jt(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Zt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=vi(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=ge(i),a=i?.endpoint??me,l=JSON.stringify(o);if(ne(i)){let u=fe(i),m=await u.getToken(),g=await Jt(a,s,m,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await Jt(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=he(i);!c&&!Xt&&(Xt=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(s.Authorization=c);let d=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function O(n,e){let t=n,i={},r=[],o=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&o.some(b=>h<b.end&&h+a.text.length>b.start);)h=t.indexOf(a.text,h+1);return h},m=u(s);if(m===-1&&(m=u(0)),m!==-1){t=t.slice(0,m)+d+t.slice(m+a.text.length);let g=d.length-a.text.length;for(let h of o)h.start>=m+a.text.length&&(h.start+=g,h.end+=g);o.push({start:m,end:m+d.length}),s=m>=s?m+d.length:s+g}r.push({...a,placeholder:d})}return{rawQuery:t,completedParams:r}}function H(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function be(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function q(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function en(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function V(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function j(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function tn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function nn(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function rn(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function on(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function sn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function nt(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function an(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);for(;a!==-1&&e.some(l=>a<l.end&&a+s.text.length>l.start);)a=n.indexOf(s.text,a+1);if(a===-1){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function ln(n,e,t=[]){let i=nt(n,e).located,r=an(n,i,t).located,o=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...r.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),s=[],a=0;for(let c of o)c.start>a&&s.push({type:"text",value:n.slice(a,c.start)}),s.push(c.segment),a=c.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function dn(n,e){let{located:t,missing:i}=nt(n,e);return{valid:t.map(r=>r.param),invalid:i}}function ye(n,e,t){let i=nt(n,e).located,{located:r,missing:o}=an(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function Pi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Ei=100,wi=300,Ti=2,Se=class{constructor(e,t,i,r,o,s,a,l={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=s;this.getAdditionalContext=a;this.callbacks=l;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===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 Zt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let c=(l.data.input??[]).filter(y=>y.source==="identified").map(y=>({id:crypto.randomUUID(),type:y.type,text:y.text})),d=tn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],m=u[u.length-1],g=this.store.get().text,h,b;if(m?.state==="in_progress"){b=!0;let y=g.toLowerCase().lastIndexOf(m.text.toLowerCase());h=y!==-1?y:o}else b=!1,h=o;let p=d.filter(y=>y.type!=="placeholder")[0],f=null;if(p&&!E($(p))){let y=q(g,h,b),w=j(p.options,y);w&&(f={id:crypto.randomUUID(),placeholder:"",type:p.type,text:w.text,kind:w.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:w.metadata,icon:w.icon,icon_svg:w.icon_svg},d=d.filter(T=>T!==p),this.callbacks.onAutoMatch?.({active:p,matched:w,rawQuery:e}))}let S=l.data.custom_fields??null,x=this.callbacks.productsForResponse?.(S);this.store.set(y=>{let w=f?[...y.completedParams,f]:y.completedParams,T=ye(y.text,w,c).valid,N=new Set(s.skippedParams.map(C=>C.id)),F=new Set(y.skippedParams.filter(C=>!N.has(C.id)).map(C=>C.type));return{suggestions:F.size>0?d.filter(C=>C.type==="placeholder"||!F.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:b,identifiedParams:T,customFields:S,...x!==void 0?{products:x}:{},...f?{completedParams:w}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=Pi(s);r===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(r===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(Ti)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ei),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),wi)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let r=this.callbacks.consumerTick?.(i,e)??"no";if(r==="asked")return!0;if(r==="owns")return!1;let o=i.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),s=H(i.text,i.filterBase,o),a=q(i.text,s,i.filterInProgress),c=i.suggestions.filter(x=>x.type!=="placeholder")[0],d=E(i.activeFormatType),m=(c&&!d?V(c.options,a):[]).filter(x=>x.is_tappable),g=c&&!d?j(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!g&&h||be(i.text,i.completedParams.length,o))return!1;let{rawQuery:b,completedParams:v}=O(i.text,i.completedParams),p=b.length<i.lastRawQuery.length,f=Math.abs(b.length-i.lastRawQuery.length),S=t&&b!==i.lastRawQuery;return p||f>=e||S?(this.doFetch(b,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ci(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function xe(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Ci(e)?e:n.ownerDocument??n}function I(n){return n.ownerDocument??n}function L(n){let t=xe(n).getSelection?.();return t||(I(n).getSelection?.()??null)}function ve(n,e){let t=n?xe(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Pe=2,Ai="magicx-aia";function cn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Oi(n){let e=I(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let r=i.scrollWidth>i.clientWidth,o=i.scrollHeight>i.clientHeight;if(r||o){let s=t.getComputedStyle(i);if(r&&cn(s.overflowX)||o&&cn(s.overflowY))return i}if(i.classList.contains(Ai))return null;i=i.parentElement}return null}function it(n){let e=L(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=Oi(n);if(!i||typeof t.getBoundingClientRect!="function")return;let r=t.getBoundingClientRect();if(r.height===0)return;let o=i.getBoundingClientRect();if(i.scrollWidth>i.clientWidth){let s=o.left+i.clientLeft,a=s+i.clientWidth;r.right>a?i.scrollLeft+=r.right-a+Pe:r.left<s&&(i.scrollLeft-=s-r.left+Pe)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+Pe:r.top<s&&(i.scrollTop-=s-r.top+Pe)}}var mn='[contenteditable="false"]',Ii="strong[data-param-id]",z;function Di(){if(z!==void 0)return z;let n=globalThis.Intl.Segmenter;if(!n)return z=null,null;try{z=new n(void 0,{granularity:"grapheme"})}catch{z=null}return z??null}function Ee(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(mn))return!0;t=t.parentNode}return!1}function we(n){return I(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Ee(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Te(n){let e=we(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function rt(n){let e=we(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function k(n){let e=L(n);if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(Ee(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=fn(r.childNodes[s],n);return o+un(r,n)}return t.nodeType!==Node.TEXT_NODE||Ee(t,n)?null:un(t,n)+i}function fn(n,e){if(n.nodeType===Node.TEXT_NODE)return Ee(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(mn))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=fn(r,e);return i}function un(n,e){let t=we(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function D(n,e){let t=I(n),i=L(n);if(!i)return;let r=Math.max(0,Math.min(e,rt(n))),o=we(n),s=0,a=null,l=0,c=o.nextNode(),d=null;for(;c;){let m=c.data.length;if(r<s+m){a=c,l=r-s;break}if(r===s+m){let g=o.nextNode();g?(a=g,l=0):(a=c,l=m);break}s+=m,d=c,c=o.nextNode()}let u=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?u.setStartBefore(m):l===a.data.length?u.setStartAfter(m):u.setStart(a,l):u.setStart(a,l)}else d?u.setStart(d,d.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u),Ri(n,i,u,r),it(n)}function pn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Ii)??null;return i&&e.contains(i)?i:null}function Ri(n,e,t,i){let r=pn(e.anchorNode,n);if(r&&r!==pn(t.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${i}:${r.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function gn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=k(n);return i!==null&&t===`${i}:${e}`}function ot(n){let e=k(n);return e==null?!1:e>=rt(n)}function st(n,e){if(e<=0)return 0;let t=Di();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function K(n,e,t=[],i={}){let{rawQuery:r,completedParams:o}=O(n,e);return{query:n.trim(),raw_query:r,completed_params:re(o,t),identified_params:ie(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function at(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?ot(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?k(n):null}var Ce=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(o),a=r(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=at(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(E(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(t.activeDropdownIndex),g=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let m=at(e.target,t),g=!!t.editingParam;if(!m&&!g)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),E(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),D(u,m);break}at(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),D(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=lt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,o):a&&a(K(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),m;if(u<0)m=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;m=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[m]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),D(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}dateEntryIndex(e,t){let i=R(new Date),r=e.filteredOptions.findIndex(s=>_(s)===i);if(r>=0)return r;let o=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?o[o.length-1]:o[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((o,s)=>o.is_tappable?s:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(e){let t=ve(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=ve(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;r;){let o=getComputedStyle(r).gridTemplateColumns;if(o&&o!=="none"){let s=o.split(" ").filter(Boolean).length;if(s>0)return s}if(r===t)break;r=r.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,r){let o=ve(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Ae=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let r=this.current;if(r&&r.key===i.key){if(r.query===i.query)return"owns";let o=Math.abs(i.query.length-r.query.length),s=i.query.length<r.query.length;if(t>1&&!s&&o<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(E(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let r=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:r};let o;try{o=t(e.query,r.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(o)){this.commit(e,o,i);return}this.setSearch(e,"loading"),this.await(e,o,r.signal,i)}async await(e,t,i,r){let o;try{let s=await t;if(i.aborted||r!==this.version)return;o=Array.isArray(s)?s:[]}catch(s){if(i.aborted||r!==this.version||Mi(s))return;this.logOnce(s),o=[]}this.commit(e,o,r)}commit(e,t,i){if(i!==this.version)return;let r=this.resolveTarget(this.store.get());if(!r||r.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let o={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:t}:s.editingParam,optionSearch:o}));else{let s={...e.suggestion,options:t};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:o}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Mi(n){return n instanceof Error&&n.name==="AbortError"}var Oe=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.filter((c,d)=>d!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=O(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:r.text,otherPills:o.map(d=>d.text)})}let a=[...s,r,...o],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var hn="/products/";function bn(n){return{id:n.source_id,title:n.title,...n.handle&&{url:`${hn}${encodeURIComponent(n.handle)}`},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function dt(n){return(n?.items.matched??[]).map(bn)}var Ie=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return dt(e)}async run(e,t,i){if(!this.isEnabled())return;let r=this.getConfig();if(!r)return;if(e.trim().length===0){this.clear(i);return}let o=()=>t.aborted||!i()||!this.owns(r);try{let s=await r.fetch(e,t);if(o())return;let a=r.transform(s),l=Array.isArray(a)?a:[],c=r.limit!=null?l.slice(0,r.limit):l;if(o())return;this.commit(c)}catch(s){if(t.aborted||Li(s)||(this.logOnce(s),o()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function Li(n){return n instanceof Error&&n.name==="AbortError"}var De="(max-width: 768px)";var ki="var(--aia-option-row-height, 37px)",_i="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function yn(n,e){return e?ct(1,Math.min(n,5)):ct(1,Math.min(n,4))}function ct(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${ki} + ${_i})`}}function pt(n,e){return!e&&n>=5}function mt(n,e,t,i){if(!(!e&&n>=5&&Ni(t,i))){let s=yn(n,e);return{...s,template:ut(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let o=6;return{...ct(2,3),template:ut(2),scrollHintIndices:n>o?[o-2,o-1]:[]}}function Ni(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function ft(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let r=getComputedStyle(n),o=n.clientWidth-(Number.parseFloat(r.paddingLeft)||0)-(Number.parseFloat(r.paddingRight)||0)-(Number.parseFloat(r.columnGap)||0);return{rowWidths:i,gridWidth:o}}function ut(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function gt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(De).matches}function Sn(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&c}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function oe(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function xn(n){if(!n)return Qe();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Fi(n){let e=ce(n);return e?Gt(e):Qe()}function vn(n,e){let t=ln(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(P=>P.type!=="placeholder"),r=i[0],o=n.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" "),s=H(n.text,Math.min(n.filterBase,n.text.length),o),l=s===0&&be(n.text,n.completedParams.length,o)?"":q(n.text,s,n.filterInProgress),c=r?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,m,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let P=n.editingParam.id,M=n.completedParams.some(si=>si.id===P),Z=n.caretOffset??n.editingAnchor,kt=M?"":n.text.slice(n.editingAnchor,Z);m=kt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=V(n.editingParam.options,kt)}else m=l.trim(),g=c,h=r?.type,u=V(c,l);let b=n.optionSearch,v=b!=null&&h!=null&&b.type===h;v&&b.status==="done"&&b.query===m&&(u=g);let p=v&&b.status==="loading",f=e.showNonTappableOptions===!1;f&&(u=u.filter(P=>P.is_tappable));let S=n.editingIdentified,x=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,y=S?S.format:$(x),w=d&&E(y)?te(n.editingParam):null;w&&(y="date-range");let T=null,N=null;if(E(y)){let P=oe({...n,actionableSuggestions:i}),M=n.dateViewMonth;T=M&&M.key===P?{year:M.year,month:M.month}:S?xn(S.iso):w?xn(w.start):Fi(n.editingParam?.text),u=je(T);let Z=n.pendingRangeStart;y==="date-range"&&Z&&Z.key===P&&(N=Z.iso)}let F=P=>f?P.is_tappable:!0,A;if(d){let P=n.editingParam?.options??[];A=n.editingParam!=null&&P.filter(F).length===0}else A=r!=null&&c.filter(F).length===0;let C=Sn({inEditMode:d||S!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:A,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),qe=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:y,dateView:T,dateRangeStart:N,placeholderText:o,optionQuery:m,isSearchingOptions:p,isDropdownOpen:C,isActivePillSelected:qe}}function Re(n){return n.mode==="fresh"?Hi(n):Bi(n)}function Hi(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(x=>x.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),c=H(e,r,l),d=q(e,c,o),u=j(a.options,d);if(!u)return null;let m=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(m),h=g>=0?g:Math.max(0,e.length-u.text.length),b=h+u.text.length,v=e.slice(h,b),f=b<e.length&&e[b]===" "?b+1:b,S={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg};return{patch:{text:e,completedParams:[...t,S],suggestions:i.filter(x=>x!==a),filterBase:f,newParamId:S.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function Bi(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(S=>S.id===i.id))return null;let s=e.slice(r,o),a=j(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=r+Math.max(0,c),u=d+a.text.length,m=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg},v=t.length,p=0;for(let S=0;S<t.length;S++){let x=e.indexOf(t[S].text,p);if(x!==-1){if(x>=g){v=S;break}p=x+t[S].text.length}}let f=[...t];return f.splice(v,0,b),{patch:{text:e,completedParams:f,newParamId:b.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Me(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var Le=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?Me(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},a=r+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let s=t.text.slice(0,r),a=t.text.slice(o),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,m=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=t.completedParams.findIndex(p=>p.id===i.id),b=t.completedParams.filter(p=>p.id!==i.id),v=h>=0?Math.min(h,b.length):b.length;b.splice(v,0,g),this.deps.store.set({text:u,completedParams:b,newParamId:g.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Re({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Wi=33,Gi=70,$i=120,qi=50,X="data-aia-placeholder-leaving",J=new WeakMap;function ke(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Vi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function En(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function wn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(En(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>wn(n,e),33+i)}function Pn(n,e){En(n,e,0),e.timer=setTimeout(()=>wn(n,e),33)}function Tn(n,e){let t=J.get(n);if(e===""){t&&(ke(t),J.delete(n)),n.removeAttribute(X),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Vi(n)){t&&ke(t),n.removeAttribute(X),J.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},r=t&&t.shown>0?t:null;if(t&&ke(t),J.set(n,i),r){n.setAttribute(X,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(X),n.isConnected&&Pn(n,i)},170);return}n.removeAttribute(X),Pn(n,i)}function Cn(n){let e=J.get(n);e&&(ke(e),J.delete(n))}var An="https://ai-autocomplete.com";function ht(n=An){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function bt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ki={selectedIso:null,selectedRange:null,rangeStart:null};function se(n){if(!E(n.activeFormatType))return Ki;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:r}=e;return{selectedIso:r?null:i,selectedRange:i&&r?ee(i,r):null,rangeStart:n.dateRangeStart}}let t=te(n.editingParam);return{selectedIso:t?null:ze(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function yt(n){return n.pendingStart?ee(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function St(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,r=n===t||i!=null&&(n===i.start||n===i.end),o=i!=null&&n>i.start&&n<i.end;return{selected:r,inRange:o}}var On="data-aia-key";function B(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(On);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);r.add(l);let c=i.get(l);c||(c=t.create(a,s),c.setAttribute(On,l)),t.update?.(c,a,s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null),o.push(c)}for(let[s,a]of i)r.has(s)||a.remove();return o}function Dn(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=Yi(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=Ue(r));let c=a.querySelector("[data-aia-date-prev]"),d=a.querySelector("[data-aia-date-next]");c&&(c.onclick=()=>s.onPreviousMonth()),d&&(d.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&Ui(u,e,t,i,o,s)}function Ui(n,e,t,i,r,o){let s=R(new Date),a=yt({pendingStart:r.rangeStart,highlightedIso:_(e[t]),selected:r.selectedRange});B(n,e,{keyOf:(l,c)=>_(l)??`pad-${c}`,create:l=>Qi(l),update:(l,c,d)=>{let u=_(c),m=St(u,{selectedIso:r.selectedIso,range:a}),g=d===t&&c.is_tappable;l.id=`${i}-option-${d}`,l.dataset.aiaIndex=String(d),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<s),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===s),l.classList.toggle("magicx-aia-date-cell--selected",m.selected),l.classList.toggle("magicx-aia-date-cell--in-range",m.inRange),c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(c),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let h=Number.parseInt(l.dataset.aiaIndex??"-1",10);h>=0&&o.onHighlight(h)}):(l.onclick=null,l.onmouseenter=null)}})}function Qi(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=Xe(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function Yi(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(In("prev","Previous month","\u2039"),t,In("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of de){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=o,i.appendChild(s)}let r=document.createElement("div");return r.className="magicx-aia-datepicker-grid",r.setAttribute("data-aia-date-grid",""),n.append(e,i,r),n}function In(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",r=>r.preventDefault()),i}var Rn=[125,69];function Mn(n,e){return e?1:n===0?.7:n===1?.4:.2}function _e(n,e,t,i,r=!1,o=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Rn.length;l++){let c=Rn[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(Mn(l,!1)),a.appendChild(d)}return}o?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();B(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.addEventListener("mousedown",d=>d.preventDefault()),c},update:(l,c,d)=>{let u=l,m=s&&d===t&&!o,g=["magicx-aia-pill"];r&&g.push("magicx-aia-pill--rounded"),o&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(Mn(d,m)),o?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(d))}})}function xt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ji="Products";function Ln(n,e,t,i,r){let o=n.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let a=document.createElement("div");a.className="magicx-aia-products-label",a.id=`${t}-products-label`,a.textContent=ji;let l=document.createElement("div");l.className="magicx-aia-products-row",l.setAttribute("data-aia-products-row",""),o.append(a,l),n.appendChild(o)}let s=o.querySelector(".magicx-aia-products-row");s&&B(s,e,{keyOf:a=>zi(a),create:a=>Xi(a,i,r),update:(a,l,c)=>{a.id=`${t}-product-${c}`,a.dataset.aiaIndex=String(c)}})}function vt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function zi(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Xi(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),n.url&&(i.href=n.url),i.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",r.appendChild(a)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,o.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,o.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,o.appendChild(a)}return i.appendChild(o),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var Ji=80,Zi=150,er=280,tr=16,Pt="--aia-option-enter-delay";function Et(n,e,t,i="below"){let r=Math.max(1,Math.floor(e)),o=Math.floor(Math.max(0,n)/r);if(i!=="above")return o*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/r));return Math.max(0,s-1-o)*80}function wt(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}var kn="http://www.w3.org/2000/svg",nr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function ir(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}function _n(n){for(let e of Array.from(n.attributes))ir(e.name,e.value)&&n.removeAttribute(e.name);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!nr.has(t.localName)||t.namespaceURI!==kn?t.remove():_n(t)}else e.remove()}function ae(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==kn||e.getElementsByTagName("parsererror").length>0?null:(_n(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function Tt(n){return n.icon&&!n.icon_svg?`${n.icon} ${n.text}`:n.text}function rr(n,e,t){let i=gt(),r=!t&&pt(e,i)?ft(n):null,o=mt(e,i,r?.rowWidths??null,r?.gridWidth??null);return n.style.gridTemplateColumns=o.template,n.style.setProperty("--aia-grid-max-height",o.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&o.scrollHintIndices.includes(a))}),o.cols}function Nn(n,e,t,i,r,o,s,a="",l="below",c=!0){let d=n.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),n.appendChild(d));let u=d.dataset.aiaGroup!==a;d.dataset.aiaGroup=a,or(d,e,t,i,r,o,s,c);let m=rr(d,e.length,s);sr(d,e.length,m,s,l),u&&(d.scrollTop=0)}function or(n,e,t,i,r,o,s,a){let l=s?"1":"0",c=n.dataset.aiaGroup??"",d=a?u=>u.icon??u.icon_svg??"":()=>"";B(n,e,{keyOf:u=>`${u.text}\0${d(u)}\0${l}\0${c}`,create:(u,m)=>{let g=ar(u,s,a);return s||(g.dataset.aiaEntering=""),g},update:(u,m,g)=>{let h=g===t&&!s;u.id=`${o}-option-${g}`,u.dataset.aiaIndex=String(g),u.setAttribute("aria-selected",String(h)),u.classList.toggle("magicx-aia-option--highlighted",h),!s&&m.is_tappable?(u.onclick=()=>{u.classList.add("magicx-aia-option--pressed"),i(m),setTimeout(()=>u.classList.remove("magicx-aia-option--pressed"),170)},u.onmouseenter=()=>{let b=Number.parseInt(u.dataset.aiaIndex??"-1",10);b>=0&&r(b)}):(u.onclick=null,u.onmouseenter=null)}})}function sr(n,e,t,i,r){for(let o of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(o.dataset.aiaIndex??"-1",10);s>=0&&o.style.setProperty(Pt,`${Et(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function ar(n,e,t){let i=document.createElement("div");i.setAttribute("role","option"),i.setAttribute("data-aia-option",""),e&&i.setAttribute("data-aia-loading",""),i.tabIndex=e||!n.is_tappable?-1:0;let r=["magicx-aia-option"];n.is_tappable?r.push("magicx-aia-option--tappable"):r.push("magicx-aia-option--non-tappable"),i.className=r.join(" ");let o=document.createElement("span");o.className="magicx-aia-option-content";let s=t&&n.icon_svg?ae(n.icon_svg):null;if(s){let l=document.createElement("span");l.className="magicx-aia-option-icon",l.setAttribute("aria-hidden","true"),l.innerHTML=s,o.appendChild(l),n.icon&&(i.dataset.aiaIcon=n.icon)}let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=Tt(n),o.appendChild(a),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,o.appendChild(l)}return i.appendChild(o),i}var Fn="magicx-aia-scroll-arrow",Hn="data-aia-scroll-arrow",Ne="data-aia-visible",lr=1e3,Bn=160,Wn="--aia-scroll-arrow-bottom",Gn="Scroll down for more options",dr=4,cr=8,ur=240;function pr(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||qn(n)){n.scrollTop=r+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/ur),u=1-(1-d)*(1-d);n.scrollTop=r+e*u,d<1?o.call(t,c):i()};o.call(t,c)}function mr(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function $n(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Fn,e.setAttribute(Hn,""),e.setAttribute("aria-label",Gn),e.setAttribute("aria-hidden","true"),e.appendChild(mr(n)),e}function fr(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function qn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ct({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),r=!1,o=null,s=null,a=null,l=v=>{v?(t.setAttribute(Ne,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(Ne),t.setAttribute("aria-hidden","true"))},c=()=>{let v=0,p=e;for(;p&&p!==n;)v+=p.offsetTop,p=p.offsetParent instanceof HTMLElement?p.offsetParent:null;let f=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0,S=n.clientHeight-(v+e.offsetHeight)+(f>0?0:cr);t.style.setProperty(Wn,`${Math.max(0,Math.round(S))}px`)},d=()=>{if(r||s!==null||a!==null)return;let v=e.querySelector("[data-aia-option][data-aia-loading]")!==null,p=e.scrollHeight-e.clientHeight-e.scrollTop;l(!v&&p>dr)},u=()=>{if(r)return;c();let v=e.getAttribute("data-aia-group")??"";if(v!==o){o=v,l(!1),s!==null&&clearTimeout(s);let p=e.querySelectorAll("[data-aia-option]").length,f=qn(e)?0:wt(p,fr(e));s=setTimeout(()=>{s=null,d()},f);return}d()},m=()=>{r||s!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,d()},Bn))};e.addEventListener("scroll",m,{passive:!0});let g=v=>v.preventDefault(),h=()=>{let v=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,p=Math.max(1,e.clientHeight-v);pr(e,p,i,m)};t.addEventListener("mousedown",g),t.addEventListener("click",h);let b=null;return i&&typeof i.ResizeObserver=="function"&&(b=new i.ResizeObserver(()=>{c(),d()}),b.observe(e)),u(),{update:u,destroy(){r||(r=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",m),t.removeEventListener("mousedown",g),t.removeEventListener("click",h),b?.disconnect(),t.removeAttribute(Ne),t.setAttribute("aria-hidden","true"))}}}var gr=[159,119,164];function He(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}var Fe=new WeakMap;function hr(n,e){let t=Fe.get(n);if(t||(t={button:$n(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Fe.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Ct({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function At(n){let e=Fe.get(n);e&&(e.controller?.destroy(),Fe.delete(n))}function Be(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:m}=e,g=s.length>0,h=a&&g,b=t.length>0,v=e.products.length>0,p=r&&(b||h||o||v);if(p?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!p){vt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let S=e.showSkipButton&&g&&!e.isInputEmpty,x=h||o&&a||S,y=f.querySelector(".magicx-aia-pill-bar");if(x){y||(y=document.createElement("div"),y.className="magicx-aia-pill-bar aia-cluster",y.setAttribute("data-nowrap",""),y.setAttribute("data-aia-pillbar",""),f.insertBefore(y,f.firstChild));let P=y.querySelector(".magicx-aia-pill-scroll");P||(P=document.createElement("span"),P.className="magicx-aia-pill-scroll",P.setAttribute("data-aia-pill-scroll",""),y.insertBefore(P,y.firstChild)),_e(P,a?s:[],0,u,!0,o&&a,l),yr(y,S,o||e.skipDisabled,s[0],m)}else y&&y.remove();let w=e.suggestions[0],T=w?`${w.type} ${w.text}`:"",N=E(e.formatType),F=N&&!o;Nn(f,N?[]:t,i,c,d,e.listboxId,o,T,e.optionsPosition??"below",e.showOptionIcons??!0),hr(n,f.querySelector(".aia-grid")),Dn(f,F?t:[],i,e.listboxId,F?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let A=f.querySelector(".magicx-aia-skeleton-bars");if(o&&(!b||N)){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let P of gr){let M=document.createElement("span");M.className="magicx-aia-skeleton-bar",M.style.width=`${P}px`,A.appendChild(M)}f.appendChild(A)}}else A&&A.remove();Ln(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),vt(n,!0);let C=f.querySelector(".magicx-aia-footer")??xr(),qe=i>=0&&!!t[i]?.is_tappable;Sr(C,bt(qe,e.isInputEmpty)),C.isConnected||f.appendChild(C),br(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function br(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function yr(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",s=>s.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Sr(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function xr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ht(),o.target="_blank",o.rel="noopener noreferrer",o.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",o.append(s,a),e.append(t,o),n.append(e),n}function Vn(n,e){let t=He(e.listboxId);return n.appendChild(t),{dropdown:t}}function Ot(n,e,t){let i=se(e);Be(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:W(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:r=>t.store.set({activeDropdownIndex:r}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:r=>t.store.set({isFocused:r})})}var vr=6,Pr=.3;function Kn(n){return n<=0?"0px":`${(-Math.min(Pr,2*vr/n)).toFixed(3)}px`}function It(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=n.showChipIcons??!0,l=t.length===0;e.dataset.aiaEmpty=l?"true":"false",Tn(e,l?o:"");let c=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}`:`${p.type}:${p.value}`).join("\0"),d=e.dataset.segKey??"",u=e.dataset.newParamId??"",m=e.dataset.editingParamId??"";if(c===d&&(i??"")===u&&(r??"")===m)return;let g=s?k(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=I(e),b=h.createDocumentFragment(),v=0;for(let p of t)if(v+=p.value.length,p.type==="completed"){let f=h.createElement("strong");f.dataset.seg="completed",f.dataset.paramId=p.param.id;let S=p.param.id===i,x=p.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];S&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&y.push("magicx-aia-segment--editing"),f.className=y.join(" "),f.style.letterSpacing=Kn(p.value.length);let w=a&&p.param.icon_svg?ae(p.param.icon_svg):null;if(w){let T=h.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=w,f.appendChild(T),p.param.icon&&(f.dataset.aiaIcon=p.param.icon)}f.appendChild(h.createTextNode(p.value)),b.appendChild(f)}else if(p.type==="identified"){let f=h.createElement("strong");f.dataset.seg="identified",f.dataset.paramId=p.param.id;let S=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===r&&S.push("magicx-aia-segment--editing"),f.className=S.join(" "),f.style.letterSpacing=Kn(p.value.length),f.textContent=p.value,b.appendChild(f)}else b.appendChild(h.createTextNode(p.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(v),g!=null&&D(e,Math.max(0,Math.min(g,v)))}var Er='<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 Un(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=Er,n}function wr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Qn(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Yn(n,e){let{listboxId:t}=e,i=He(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",r.setAttribute("data-aia-input-wrapper",""),n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",wr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=Un(),r.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),r.appendChild(c));let d=new AbortController,{signal:u}=d,m=!1,g=0,h=()=>{let p=Te(s),S=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(S)},b=()=>{let p=L(s);if(!p||p.rangeCount===0)return null;let f=p.anchorNode;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(r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(g=performance.now(),h(),e.handleCaretAfterInput(k(s)))},{signal:u}),I(s).addEventListener("selectionchange",()=>{let p=L(s);if(!p||p.rangeCount===0||!s.contains(p.anchorNode))return;let f=p.isCollapsed?b():null,S=e.store.get(),x=S.editingParam?.id??S.editingIdentified?.id??null;if(f&&f!==x){e.startEditingParam(f);return}performance.now()-g<50||e.handleCaretMove(k(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",p=>{let f=p,S=f.inputType;if(S==="insertParagraph"||S==="insertLineBreak"||S==="insertFromDrop"){p.preventDefault();return}if(S.startsWith("insert")||S.startsWith("delete")){let x=S.startsWith("delete")?"":f.data??"";e.replaceEditingRange(x)&&p.preventDefault()}},{signal:u}),s.addEventListener("paste",p=>{p.preventDefault();let f=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let S=I(s),x=L(s);if(!x||x.rangeCount===0)return;let y=x.getRangeAt(0);if(!s.contains(y.startContainer))return;y.deleteContents();let w=S.createTextNode(f);y.insertNode(w),y.setStartAfter(w),y.collapse(!0),x.removeAllRanges(),x.addRange(y),h()},{signal:u}),s.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",p=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit(K(f.text,f.completedParams,f.skippedParams,{identifiedParams:f.identifiedParams,isReady:f.isReady,customFields:f.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let p=I(s),f=L(s),S=f&&f.rangeCount>0&&s.contains(f.anchorNode);if(f&&!S){let x=p.createRange();x.selectNodeContents(s),x.collapse(!0),f.removeAllRanges(),f.addRange(x)}}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>Qn(s,a));p.observe(s),d.signal.addEventListener("abort",()=>p.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function Dt(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let p=!!e.text||e.completedParams.length>0;s.disabled=!p}let m=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==m;if(It({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0}),a==="inline"){let p=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;p||e.actionableSuggestions.length>0?_e(r,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):xt(r)}else xt(r);Qn(i,r),g?(i.focus(),D(i,e.caretOffset??e.text.length)):e.isFocused&&Te(i)!==e.text&&D(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:W(e.editingIdentified.type),required:!0,options:[]}:null,b=h??e.actionableSuggestions[0],v=se(e);Be(o,{suggestions:b?[{...b,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:p=>d.set({activeDropdownIndex:p}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:p=>d.set({isFocused:p})})}function jn(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=en(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",c=`${r}${l?" ":""}${e.text} `,d=(o||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(b=>b.text!==e.text).map(b=>b.text)},consumedSuggestion:t,remainingActionable:h}}function Rt(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!r){r=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let m of t)m(d,u)}}catch(l){throw i.length=0,l}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function zn(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let l={...a,...r(a)},c={...s,...r(s)};o(c,l)})}}var Mt=new WeakSet,Xn=new WeakMap;function Zn(n){return n.nodeType===Node.DOCUMENT_NODE}function Tr(n){return Zn(n)?n:n.ownerDocument}function Cr(n){let e=Xn.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(ti),Xn.set(n,i),i)}catch{return null}}function Jn(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ti,e.appendChild(t)}function ei(n){if(typeof document>"u")return;let e=n??document;if(Mt.has(e))return;let t=Tr(e);if(Zn(e)){let o=e.head??e.documentElement;if(!o)return;Jn(t,o),Mt.add(e);return}let i=Cr(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):Jn(t,e),Mt.add(e)}var ti=`.aia-stack {
2
+ display: flex;
3
+ flex-direction: column;
4
+ gap: var(--aia-stack-space, 0.5rem);
17
5
  }
18
-
19
- @layer layout {
20
- .aia-cluster {
21
- display: flex;
22
- flex-wrap: wrap;
23
- gap: var(--aia-cluster-gap, 0.5rem);
24
- }
25
- .aia-cluster[data-nowrap] {
26
- flex-wrap: nowrap;
27
- }
28
- .aia-cluster[data-align="start"] {
29
- align-items: start;
30
- }
31
- .aia-cluster[data-align="center"] {
32
- align-items: center;
33
- }
34
- .aia-cluster[data-align="end"] {
35
- align-items: end;
36
- }
37
- .aia-cluster[data-align="baseline"] {
38
- align-items: baseline;
39
- }
40
- .aia-cluster[data-justify="start"] {
41
- justify-content: start;
42
- }
43
- .aia-cluster[data-justify="center"] {
44
- justify-content: center;
45
- }
46
- .aia-cluster[data-justify="end"] {
47
- justify-content: end;
48
- }
49
- .aia-cluster[data-justify="between"] {
50
- justify-content: space-between;
51
- }
52
- .aia-cluster[data-justify="around"] {
53
- justify-content: space-around;
54
- }
6
+ .aia-stack[data-align="start"] {
7
+ align-items: start;
8
+ }
9
+ .aia-stack[data-align="center"] {
10
+ align-items: center;
11
+ }
12
+ .aia-stack[data-align="end"] {
13
+ align-items: end;
55
14
  }
15
+ /* data-align="stretch" is the flex default \u2014 no rule needed. */
56
16
 
57
- @layer layout {
58
- .aia-grid {
59
- display: grid;
60
- grid-template-columns: repeat(
61
- auto-fit,
62
- minmax(min(var(--aia-grid-min), 100%), var(--aia-grid-max, 1fr))
63
- );
64
- gap: var(--aia-grid-gap, 0);
65
- }
17
+ .aia-cluster {
18
+ display: flex;
19
+ flex-wrap: wrap;
20
+ gap: var(--aia-cluster-gap, 0.5rem);
21
+ }
22
+ .aia-cluster[data-nowrap] {
23
+ flex-wrap: nowrap;
24
+ }
25
+ .aia-cluster[data-align="start"] {
26
+ align-items: start;
27
+ }
28
+ .aia-cluster[data-align="center"] {
29
+ align-items: center;
30
+ }
31
+ .aia-cluster[data-align="end"] {
32
+ align-items: end;
33
+ }
34
+ .aia-cluster[data-align="baseline"] {
35
+ align-items: baseline;
36
+ }
37
+ .aia-cluster[data-justify="start"] {
38
+ justify-content: start;
39
+ }
40
+ .aia-cluster[data-justify="center"] {
41
+ justify-content: center;
42
+ }
43
+ .aia-cluster[data-justify="end"] {
44
+ justify-content: end;
45
+ }
46
+ .aia-cluster[data-justify="between"] {
47
+ justify-content: space-between;
48
+ }
49
+ .aia-cluster[data-justify="around"] {
50
+ justify-content: space-around;
51
+ }
66
52
 
67
- /* Scrollable variant \u2014 capped height with a styled thin scrollbar. Rows pack
68
- from the top instead of stretching to fill the container. */
69
- .aia-grid[data-scroll] {
70
- grid-auto-rows: min-content;
71
- align-content: start;
72
- justify-content: start;
73
- /* The scroll box's reserved band (--aia-grid-scroll-* / --aia-grid-overlap-*)
74
- is deliberately NOT declared here \u2014 see the unlayered rule in
75
- appearance.css for why. */
76
- max-height: var(--aia-grid-max-height, 120px);
77
- overflow-y: auto;
78
- scrollbar-width: thin;
79
- scrollbar-color: var(--aia-scrollbar-thumb, rgba(255, 255, 255, 0.3)) transparent;
80
- }
81
- .aia-grid[data-scroll]::-webkit-scrollbar {
82
- width: 6px;
83
- }
84
- .aia-grid[data-scroll]::-webkit-scrollbar-track {
85
- background: transparent;
86
- }
87
- .aia-grid[data-scroll]::-webkit-scrollbar-thumb {
88
- background: var(--aia-scrollbar-thumb, rgba(255, 255, 255, 0.3));
89
- border-radius: 3px;
90
- }
53
+ .aia-grid {
54
+ display: grid;
55
+ grid-template-columns: repeat(
56
+ auto-fit,
57
+ minmax(min(var(--aia-grid-min), 100%), var(--aia-grid-max, 1fr))
58
+ );
59
+ gap: var(--aia-grid-gap, 0);
60
+ }
61
+
62
+ /* Scrollable variant \u2014 capped height with a styled thin scrollbar. Rows pack
63
+ from the top instead of stretching to fill the container. */
64
+ .aia-grid[data-scroll] {
65
+ grid-auto-rows: min-content;
66
+ align-content: start;
67
+ justify-content: start;
68
+ /* The scroll box's reserved band (--aia-grid-scroll-* / --aia-grid-overlap-*)
69
+ is deliberately NOT declared here \u2014 see the rule in
70
+ appearance.css for why. */
71
+ max-height: var(--aia-grid-max-height, 120px);
72
+ overflow-y: auto;
73
+ scrollbar-width: thin;
74
+ scrollbar-color: var(--aia-scrollbar-thumb, rgba(255, 255, 255, 0.3)) transparent;
75
+ }
76
+ .aia-grid[data-scroll]::-webkit-scrollbar {
77
+ width: 6px;
78
+ }
79
+ .aia-grid[data-scroll]::-webkit-scrollbar-track {
80
+ background: transparent;
81
+ }
82
+ .aia-grid[data-scroll]::-webkit-scrollbar-thumb {
83
+ background: var(--aia-scrollbar-thumb, rgba(255, 255, 255, 0.3));
84
+ border-radius: 3px;
91
85
  }
92
86
 
93
87
  /* ===================================================================
@@ -1366,13 +1360,94 @@ function Ve(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
1366
1360
  * mix explicit dimensions with padding (e.g. .magicx-aia-pill has height:36px
1367
1361
  * + padding:13px) and were authored assuming \`border-box\`. In consumer apps
1368
1362
  * without a global \`* { box-sizing: border-box }\` reset the pill rendered
1369
- * ~62px tall instead of 36px. Scoping the reset to \`.magicx-aia\` descendants
1370
- * keeps the library self-contained without leaking onto consumer markup.
1363
+ * ~62px tall instead of 36px. The root gets it here; everything under the SDK's
1364
+ * own roots gets it from the isolation rule below, and nothing else does.
1371
1365
  */
1372
- :where(.magicx-aia, .magicx-aia *, .magicx-aia *::before, .magicx-aia *::after) {
1366
+ :where(.magicx-aia) {
1373
1367
  box-sizing: border-box;
1374
1368
  }
1375
1369
 
1370
+ /*
1371
+ * Consumer isolation. Everything the SDK renders sits under one of two roots
1372
+ * it owns \u2014 the Tier 1 input wrapper and the dropdown \u2014 and every element
1373
+ * under them rolls its author-level styles back to the browser defaults
1374
+ * (\`all: revert\`) before the SDK's own rules apply. A page's element and
1375
+ * universal rules (\`button { \u2026 }\`, \`a { \u2026 }\`, \`* { \u2026 }\`, a CSS reset, a
1376
+ * framework's preflight) therefore never reach the widget.
1377
+ *
1378
+ * The selector is shaped for specificity (0,0,5) on purpose:
1379
+ * - \`:where(...)\` contributes nothing, so the scope never outranks anything;
1380
+ * - five \`:not(html)\` add one type-level unit each \u2014 enough to beat any
1381
+ * type-only page selector up to five compounds deep (\`html body main form
1382
+ * button\`), and still below every rule that names a class, attribute or id.
1383
+ * The SDK's own class rules, and a consumer's intentional overrides on the
1384
+ * \`data-aia-*\` hooks, therefore win exactly as before.
1385
+ *
1386
+ * Left alone: the roots' ancestors (the consumer's container), inline SVG
1387
+ * (\`revert\` strips presentation attributes such as \`stroke\` and \`d\`, which
1388
+ * would blank the icons), and the consumer's own submit button and whatever
1389
+ * is inside it (\`[data-aia-submit-slot]\`). Custom properties are outside
1390
+ * \`all\`, so \`--aia-*\` theming still flows in from the page.
1391
+ *
1392
+ * Every SDK rule must therefore carry at least one class or attribute; a
1393
+ * type-only or \`:where()\`-only rule would lose to this one, and a rule inside
1394
+ * a cascade layer would lose to it whatever its specificity.
1395
+ * \`packages/vanilla/tests/packaging/consumerIsolation.test.ts\` enforces both
1396
+ * and keeps the four copies of this block identical.
1397
+ */
1398
+ :where(
1399
+ [data-aia-input-wrapper],
1400
+ [data-aia-input-wrapper] *,
1401
+ [data-aia-dropdown],
1402
+ [data-aia-dropdown] *
1403
+ ):not(:where(svg, svg *, [data-aia-submit-slot], [data-aia-submit-slot] *)):not(html):not(
1404
+ html
1405
+ ):not(html):not(html):not(html),
1406
+ :where(
1407
+ [data-aia-input-wrapper],
1408
+ [data-aia-input-wrapper] *,
1409
+ [data-aia-dropdown],
1410
+ [data-aia-dropdown] *
1411
+ ):not(:where(svg, svg *, [data-aia-submit-slot], [data-aia-submit-slot] *)):not(html):not(
1412
+ html
1413
+ ):not(html):not(html):not(html)::before,
1414
+ :where(
1415
+ [data-aia-input-wrapper],
1416
+ [data-aia-input-wrapper] *,
1417
+ [data-aia-dropdown],
1418
+ [data-aia-dropdown] *
1419
+ ):not(:where(svg, svg *, [data-aia-submit-slot], [data-aia-submit-slot] *)):not(html):not(
1420
+ html
1421
+ ):not(html):not(html):not(html)::after {
1422
+ all: revert;
1423
+ box-sizing: border-box;
1424
+ }
1425
+
1426
+ /* Inherited typography stops at the roots too. \`revert\` leaves an inherited
1427
+ property to inherit, so a page's \`body { line-height: 1.8; letter-spacing:
1428
+ 0.05em; text-transform: uppercase }\` would still flow into the widget through
1429
+ its container. The font itself (family, size, weight) and the text colour are
1430
+ meant to come from the page \u2014 see --aia-font-family \u2014 so they keep
1431
+ inheriting; the adjustments below return to their initial values at the two
1432
+ roots and inherit from there. Same specificity as the reset above and after
1433
+ it in source order, so it wins the tie on the roots. */
1434
+ :where([data-aia-input-wrapper], [data-aia-dropdown]):not(html):not(html):not(html):not(html):not(
1435
+ html
1436
+ ) {
1437
+ line-height: normal;
1438
+ letter-spacing: normal;
1439
+ word-spacing: normal;
1440
+ text-transform: none;
1441
+ text-indent: 0;
1442
+ text-align: start;
1443
+ text-shadow: none;
1444
+ font-style: normal;
1445
+ font-variant: normal;
1446
+ white-space: normal;
1447
+ visibility: visible;
1448
+ cursor: auto;
1449
+ }
1450
+
1376
1451
  /*
1377
1452
  * Primitive color ramp \u2014 single source of truth, mirroring the Figma
1378
1453
  * "Primitives" collection. INTERNAL: theme via the public --aia-* vars below,
@@ -1577,11 +1652,11 @@ function Ve(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
1577
1652
  --aia-footer-fade-lead: 0px;
1578
1653
  }
1579
1654
 
1580
- /* The reserved band the footer overlaps, kept OUT of \`@layer layout\` on
1581
- purpose. A consumer reset (\`* { margin: 0; padding: 0 }\`, Tailwind's
1582
- preflight, \u2026) is unlayered, and an unlayered declaration beats every layered
1583
- one no matter its specificity \u2014 inside the layer this padding and margin
1584
- were silently zeroed and the footer had nothing to sit over. */
1655
+ /* The reserved band the footer overlaps. Declared here, apart from the grid
1656
+ primitive, because it is the dropdown's concern rather than the grid's \u2014 and
1657
+ it once lived inside a \`@layer layout\` block, where a consumer's unlayered
1658
+ reset zeroed it silently. No SDK rule is layered any more (the isolation
1659
+ rule above is unlayered, and a layered rule would lose to it). */
1585
1660
  [data-aia-dropdown] .aia-grid[data-scroll] {
1586
1661
  padding-top: var(--aia-grid-scroll-top, 0);
1587
1662
  padding-bottom: var(--aia-grid-scroll-bottom, 0);