@magicx-eng/ai-autocomplete-vanilla 0.23.2 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var xt=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var yi=Object.getOwnPropertyNames;var Si=Object.prototype.hasOwnProperty;var xi=(n,e)=>{for(var t in e)xt(n,t,{get:e[t],enumerable:!0})},vi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yi(e))!Si.call(n,r)&&r!==t&&xt(n,r,{get:()=>e[r],enumerable:!(i=bi(e,r))||i.enumerable});return n};var Pi=n=>vi(xt({},"__esModule",{value:!0}),n);var Vr={};xi(Vr,{AIAutocomplete:()=>yt,ATTRIBUTION_URL:()=>Nt,DATE_RANGE_META_END:()=>Pe,DATE_RANGE_META_START:()=>ve,ModeController:()=>re,OPTIONS_GRID_MOBILE_QUERY:()=>ue,OPTION_ENTER_DELAY_VAR:()=>ot,OPTION_ENTER_FADE_MS:()=>Kn,OPTION_ENTER_RISE_MS:()=>Un,OPTION_ENTER_RISE_PX:()=>Qn,OPTION_ENTER_STAGGER_MS:()=>Vn,PLACEHOLDER_FADE_OUT_MS:()=>Mn,PLACEHOLDER_LEAVING_ATTR:()=>Y,PLACEHOLDER_SWAP_GAP_MS:()=>Ln,PLACEHOLDER_TYPE_MS:()=>Dn,PLACEHOLDER_WORD_PAUSE_MS:()=>Rn,PRODUCT_PATH_PREFIX:()=>Mt,RANGE_SEPARATOR:()=>Ct,SCROLL_ARROW_ATTR:()=>Wt,SCROLL_ARROW_BOTTOM_VAR:()=>$t,SCROLL_ARROW_CLASS:()=>Bt,SCROLL_ARROW_FADE_MS:()=>Xn,SCROLL_ARROW_LABEL:()=>qt,SCROLL_ARROW_SCROLL_IDLE_MS:()=>Gt,SCROLL_ARROW_VISIBLE_ATTR:()=>me,SKIPPED_PARAM_TEXT:()=>Ot,WEEKDAY_LABELS:()=>se,addMonths:()=>ge,attachScrollArrow:()=>dt,buildAttributionUrl:()=>et,buildDateOptions:()=>he,buildQuery:()=>A,buildSubmitResult:()=>$,cellDay:()=>ye,cellIso:()=>k,computeOptionsGridLayout:()=>_t,createStore:()=>ft,cursorIsAtEnd:()=>He,dateCellMarks:()=>it,dateSelectionFor:()=>ne,extractPlainText:()=>ce,formatAbsoluteDate:()=>V,formatDate:()=>Et,formatDateRange:()=>At,getCursorOffset:()=>M,getFooterHint:()=>tt,identifiedParamLabel:()=>H,isCalendarFormat:()=>P,isOptionsGridMobileViewport:()=>je,isoDate:()=>D,measureOptionsGrid:()=>Ye,monthLabel:()=>fe,needsOptionsGridMeasurement:()=>Ue,optionEnterDelayMs:()=>st,optionLabel:()=>lt,optionsEntranceDurationMs:()=>at,optionsGridTemplateColumns:()=>Ke,parseDate:()=>ae,parseLooseDate:()=>B,parseLooseDateRange:()=>K,plainTextLength:()=>Fe,planOptionsGrid:()=>Qe,previousGraphemeBoundary:()=>Be,productFromMatchedItem:()=>Lt,productsFromCustomFields:()=>qe,renderEditableContent:()=>mt,resolveFormatType:()=>W,resolveIdentifiedDate:()=>xe,sanitizeOptionIconSvg:()=>ie,scrollCaretIntoView:()=>ke,selectedIsoFromText:()=>be,selectedRangeFor:()=>z,setCursorOffset:()=>I,toWireIdentifiedParams:()=>X,visibleDateRange:()=>nt,withSkippedParams:()=>J});module.exports=Pi(Vr);function vt(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function H(n){let e=vt(n);return e.length>0?e.join(" "):n}var j=["January","February","March","April","May","June","July","August","September","October","November","December"],se=["S","M","T","W","T","F","S"],Xt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Jt="aiaDate",Zt="aiaDay",jt=n=>String(n).padStart(2,"0");function D(n){return`${n.getFullYear()}-${jt(n.getMonth()+1)}-${jt(n.getDate())}`}function Pt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Ei(n){let e=Pt(n).getTime()-Pt(new Date).getTime();return Math.round(e/864e5)}function Et(n){let e=Ei(n);return e>=0&&e<7?Xt[n.getDay()]:V(n)}function V(n){return n.getFullYear()===new Date().getFullYear()?`${j[n.getMonth()]} ${n.getDate()}`:`${j[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ae(n){if(!n)return null;let e=Xt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Pt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=j.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 fe(n){return`${j[n.month]} ${n.year}`}function wt(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function en(n){return{year:n.getFullYear(),month:n.getMonth()}}function ge(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function zt(){return{text:"",is_tappable:!1,kind:null}}function he(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(zt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Et(o),is_tappable:!0,kind:null,metadata:{[Jt]:D(o),[Zt]:r}})}for(;i.length%se.length!==0;)i.push(zt());return i}function be(n){let e=ae(n);return e?D(e):null}function k(n){let e=n?.metadata?.[Jt];return typeof e=="string"?e:null}function ye(n){let e=n?.metadata?.[Zt];return typeof e=="number"?e:null}function wi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function tn(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:j.findIndex(t=>t.toLowerCase().startsWith(e))}function Ti(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 nn(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function B(n,e={}){if(!n)return null;let t=e.today??new Date,i=wi(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=nn(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?D(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=tn(o[1]);if(l>=0)return Se(l,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=tn(s[2]);if(l>=0)return Se(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?Se(c-1,l,a[3],t):c>12&&l<=12?Se(l-1,c,a[3],t):null}return null}function Se(n,e,t,i){if(t){if(t.length!==4)return null;let o=nn(Number(t),n,e);return o?D(o):null}let r=Ti(n,e,i);return r?D(r):null}function xe(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:B(n.text,e)}var Ct=" - ",ve="aiaDateRangeStart",Pe="aiaDateRangeEnd";function le(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Tt=/^\d{4}-\d{2}-\d{2}$/;function rn(n){if(!Tt.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,Ai=/[-–—]/g;function Oi(n){let e=[];for(let t of[Ci,Ai]){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 K(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[r,o]of Oi(n.trim())){let s=B(r.trim(),e);if(!s)continue;let a=B(o.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function At(n){let e=rn(n.start),t=rn(n.end);return!e||!t?"":n.start===n.end?V(e):`${V(e)}${Ct}${V(t)}`}function on(n,e){let t=le(n,e);return{text:At(t),is_tappable:!0,kind:null,metadata:{[ve]:t.start,[Pe]:t.end}}}function z(n,e={}){let t=n?.metadata?.[ve],i=n?.metadata?.[Pe];return typeof t=="string"&&typeof i=="string"&&Tt.test(t)&&Tt.test(i)?le(t,i):K(n?.text,e)}function P(n){return n==="date"||n==="date-range"}var Ii=new Set(["date","dates"]),Di=new Set(["range","ranges","span","period","window"]),sn=3;function Ri(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(K(t.text)!==null?e.range+=1:B(t.text)!==null&&(e.single+=1));return e}function W(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Ri(n.options);if(t.single+t.range>=sn&&t.range>t.single)return"date-range";let i=vt(n.type);return i.some(r=>Ii.has(r))?i.some(r=>Di.has(r))?"date-range":"date":t.single>=sn?"date":"options"}var Ee=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 Mi="https://api.ai-autocomplete.com",we=`${Mi}/api/suggest`,an=new WeakMap;function de(n){return n?.type==="accessToken"}function Li(n){if(!(!n||de(n)))return n}function Te(n){let e=an.get(n.getAccessToken);return e||(e=new Ee(n),an.set(n.getAccessToken,e)),e}function Ce(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ae(n){let e=Li(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function X(n){return n.map(e=>({type:e.type,value:e.text}))}var Ot="skipped";function J(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:Ot,kind:null}));return i.length>0?[...n,...i]:n}var ki="0.23.2",ln=!1;function _i(){return crypto.randomUUID()}function Ni(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Fi(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:J(e.map(d=>Ni(d,t)),s??[]),...r&&r.length>0&&{identified_params:X(r)},...o&&o.length>0&&{recently_suggested:o},...c!=null&&{contact_account_count:c},...a!==void 0&&{additional_context:a}},meta:{request_id:_i(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ki,session_id:i}}}async function dn(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function cn(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=Fi(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Ce(i),a=i?.endpoint??we,l=JSON.stringify(o);if(de(i)){let u=Te(i),m=await u.getToken(),g=await dn(a,s,m,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await dn(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=Ae(i);!c&&!ln&&(ln=!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 A(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 G(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Oe(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function U(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 un(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 Q(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 Z(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 pn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function mn(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 fn(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 gn(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 hn(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 It(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 bn(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 yn(n,e,t=[]){let i=It(n,e).located,r=bn(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 Sn(n,e){let{located:t,missing:i}=It(n,e);return{valid:t.map(r=>r.param),invalid:i}}function Ie(n,e,t){let i=It(n,e).located,{located:r,missing:o}=bn(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function Hi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Bi=100,Wi=300,Gi=2,De=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?gn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await cn(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=pn(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&&!P(W(p))){let y=U(g,h,b),w=Z(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=Ie(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=Hi(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(Gi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Bi),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=G(i.text,i.filterBase,o),a=U(i.text,s,i.filterInProgress),c=i.suggestions.filter(x=>x.type!=="placeholder")[0],d=P(i.activeFormatType),m=(c&&!d?Q(c.options,a):[]).filter(x=>x.is_tappable),g=c&&!d?Z(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!g&&h||Oe(i.text,i.completedParams.length,o))return!1;let{rawQuery:b,completedParams:v}=A(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 $i(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function Re(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&$i(e)?e:n.ownerDocument??n}function R(n){return n.ownerDocument??n}function _(n){let t=Re(n).getSelection?.();return t||(R(n).getSelection?.()??null)}function Me(n,e){let t=n?Re(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Le=2,qi="magicx-aia";function xn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Vi(n){let e=R(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&&xn(s.overflowX)||o&&xn(s.overflowY))return i}if(i.classList.contains(qi))return null;i=i.parentElement}return null}function ke(n){let e=_(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=Vi(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+Le:r.left<s&&(i.scrollLeft-=s-r.left+Le)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+Le:r.top<s&&(i.scrollTop-=s-r.top+Le)}}var En='[contenteditable="false"]',Ki="strong[data-param-id]",ee;function Ui(){if(ee!==void 0)return ee;let n=globalThis.Intl.Segmenter;if(!n)return ee=null,null;try{ee=new n(void 0,{granularity:"grapheme"})}catch{ee=null}return ee??null}function _e(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(En))return!0;t=t.parentNode}return!1}function Ne(n){return R(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return _e(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ce(n){let e=Ne(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Fe(n){let e=Ne(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function M(n){let e=_(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(_e(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=wn(r.childNodes[s],n);return o+vn(r,n)}return t.nodeType!==Node.TEXT_NODE||_e(t,n)?null:vn(t,n)+i}function wn(n,e){if(n.nodeType===Node.TEXT_NODE)return _e(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(En))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=wn(r,e);return i}function vn(n,e){let t=Ne(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 I(n,e){let t=R(n),i=_(n);if(!i)return;let r=Math.max(0,Math.min(e,Fe(n))),o=Ne(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),Qi(n,i,u,r),ke(n)}function Pn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Ki)??null;return i&&e.contains(i)?i:null}function Qi(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 Tn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=M(n);return i!==null&&t===`${i}:${e}`}function He(n){let e=M(n);return e==null?!1:e>=Fe(n)}function Be(n,e){if(e<=0)return 0;let t=Ui();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 $(n,e,t=[],i={}){let{rawQuery:r,completedParams:o}=A(n,e);return{query:n.trim(),raw_query:r,completed_params:J(o,t),identified_params:X(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Dt(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")?He(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Rt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?M(n):null}var We=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=Dt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=P(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(P(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=Dt(e.target,t),g=!!t.editingParam;if(!m&&!g)break;e.preventDefault();let h=P(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(),P(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(),P(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?.(),I(u,m);break}Dt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%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=Rt(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?.(),I(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=Rt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Rt(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($(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?.(),I(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=D(new Date),r=e.filteredOptions.findIndex(s=>k(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=Me(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=Me(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=Me(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Ge=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(P(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||Yi(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 Yi(n){return n instanceof Error&&n.name==="AbortError"}var $e=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}=A(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 Mt="/products/";function Lt(n){return{id:n.source_id,title:n.title,...n.handle&&{url:`${Mt}${encodeURIComponent(n.handle)}`},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function qe(n){return(n?.items.matched??[]).map(Lt)}var Ve=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 qe(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||ji(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 ji(n){return n instanceof Error&&n.name==="AbortError"}var ue="(max-width: 768px)";var zi="var(--aia-option-row-height, 37px)",Xi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function _t(n,e){return e?kt(1,Math.min(n,5)):kt(1,Math.min(n,4))}function kt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${zi} + ${Xi})`}}function Ue(n,e){return!e&&n>=5}function Qe(n,e,t,i){if(!(!e&&n>=5&&Ji(t,i))){let s=_t(n,e);return{...s,template:Ke(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let o=6;return{...kt(2,3),template:Ke(2),scrollHintIndices:n>o?[o-2,o-1]:[]}}function Ji(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 Ye(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 Ke(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function je(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(ue).matches}function Cn(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 pe(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 An(n){if(!n)return wt();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Zi(n){let e=ae(n);return e?en(e):wt()}function On(n,e){let t=yn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(E=>E.type!=="placeholder"),r=i[0],o=n.suggestions.filter(E=>E.type==="placeholder").map(E=>E.text).join(" "),s=G(n.text,Math.min(n.filterBase,n.text.length),o),l=s===0&&Oe(n.text,n.completedParams.length,o)?"":U(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 E=n.editingParam.id,L=n.completedParams.some(hi=>hi.id===E),oe=n.caretOffset??n.editingAnchor,Yt=L?"":n.text.slice(n.editingAnchor,oe);m=Yt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=Q(n.editingParam.options,Yt)}else m=l.trim(),g=c,h=r?.type,u=Q(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(E=>E.is_tappable));let S=n.editingIdentified,x=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,y=S?S.format:W(x),w=d&&P(y)?z(n.editingParam):null;w&&(y="date-range");let T=null,N=null;if(P(y)){let E=pe({...n,actionableSuggestions:i}),L=n.dateViewMonth;T=L&&L.key===E?{year:L.year,month:L.month}:S?An(S.iso):w?An(w.start):Zi(n.editingParam?.text),u=he(T);let oe=n.pendingRangeStart;y==="date-range"&&oe&&oe.key===E&&(N=oe.iso)}let F=E=>f?E.is_tappable:!0,O;if(d){let E=n.editingParam?.options??[];O=n.editingParam!=null&&E.filter(F).length===0}else O=r!=null&&c.filter(F).length===0;let C=Cn({inEditMode:d||S!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:O,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),St=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:St}}function ze(n){return n.mode==="fresh"?er(n):tr(n)}function er(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=G(e,r,l),d=U(e,c,o),u=Z(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 tr(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=Z(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 Xe(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 Je=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===""?Xe(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:A(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=ze({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 Dn=33,Rn=70,Mn=120,Ln=50,Y="data-aia-placeholder-leaving",te=new WeakMap;function Ze(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function nr(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function kn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function _n(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(kn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>_n(n,e),33+i)}function In(n,e){kn(n,e,0),e.timer=setTimeout(()=>_n(n,e),33)}function Nn(n,e){let t=te.get(n);if(e===""){t&&(Ze(t),te.delete(n)),n.removeAttribute(Y),delete n.dataset.placeholder;return}if(t?.target===e)return;if(nr(n)){t&&Ze(t),n.removeAttribute(Y),te.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&&Ze(t),te.set(n,i),r){n.setAttribute(Y,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(Y),n.isConnected&&In(n,i)},170);return}n.removeAttribute(Y),In(n,i)}function Fn(n){let e=te.get(n);e&&(Ze(e),te.delete(n))}var Nt="https://ai-autocomplete.com";function et(n=Nt){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 tt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var ir={selectedIso:null,selectedRange:null,rangeStart:null};function ne(n){if(!P(n.activeFormatType))return ir;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:r}=e;return{selectedIso:r?null:i,selectedRange:i&&r?le(i,r):null,rangeStart:n.dateRangeStart}}let t=z(n.editingParam);return{selectedIso:t?null:be(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function nt(n){return n.pendingStart?le(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function it(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 Hn="data-aia-key";function q(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Hn);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(Hn,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 Wn(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=sr(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=fe(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&&rr(u,e,t,i,o,s)}function rr(n,e,t,i,r,o){let s=D(new Date),a=nt({pendingStart:r.rangeStart,highlightedIso:k(e[t]),selected:r.selectedRange});q(n,e,{keyOf:(l,c)=>k(l)??`pad-${c}`,create:l=>or(l),update:(l,c,d)=>{let u=k(c),m=it(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 or(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=ye(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 sr(){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(Bn("prev","Previous month","\u2039"),t,Bn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of se){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 Bn(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 Gn=[125,69];function $n(n,e){return e?1:n===0?.7:n===1?.4:.2}function rt(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<Gn.length;l++){let c=Gn[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($n(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();q(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($n(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 Ft(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ar="Products";function qn(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=ar;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&&q(s,e,{keyOf:a=>lr(a),create:a=>dr(a,i,r),update:(a,l,c)=>{a.id=`${t}-product-${c}`,a.dataset.aiaIndex=String(c)}})}function Ht(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function lr(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function dr(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 Vn=80,Kn=150,Un=280,Qn=16,ot="--aia-option-enter-delay";function st(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 at(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 Yn="http://www.w3.org/2000/svg",cr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function ur(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var pr=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],mr=/^[a-zA-Z0-9#.,%\s()-]+$/;function fr(n){let e=[];for(let t of pr){let i=n.getAttribute(t);i===null||!mr.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function jn(n){for(let e of Array.from(n.attributes))ur(e.name,e.value)&&n.removeAttribute(e.name);fr(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!cr.has(t.localName)||t.namespaceURI!==Yn?t.remove():jn(t)}else e.remove()}function ie(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!==Yn||e.getElementsByTagName("parsererror").length>0?null:(jn(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function lt(n){return n.text}function gr(n,e,t){let i=je(),r=!t&&Ue(e,i)?Ye(n):null,o=Qe(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 zn(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,hr(d,e,t,i,r,o,s,c);let m=gr(d,e.length,s);br(d,e.length,m,s,l),u&&(d.scrollTop=0)}function hr(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??"":()=>"";q(n,e,{keyOf:u=>`${u.text}\0${d(u)}\0${l}\0${c}`,create:(u,m)=>{let g=yr(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 br(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(ot,`${st(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function yr(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?ie(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=lt(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 Bt="magicx-aia-scroll-arrow",Wt="data-aia-scroll-arrow",me="data-aia-visible",Xn=1e3,Gt=160,$t="--aia-scroll-arrow-bottom",qt="Scroll down for more options",Sr=4,xr=8,vr=240;function Pr(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||Zn(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)/vr),u=1-(1-d)*(1-d);n.scrollTop=r+e*u,d<1?o.call(t,c):i()};o.call(t,c)}function Er(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Jn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Bt,e.setAttribute(Wt,""),e.setAttribute("aria-label",qt),e.setAttribute("aria-hidden","true"),e.appendChild(Er(n)),e}function wr(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Zn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function dt({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(me,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(me),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:xr);t.style.setProperty($t,`${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>Sr)},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=Zn(e)?0:at(p,wr(e));s=setTimeout(()=>{s=null,d()},f);return}d()},m=()=>{r||s!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,d()},Gt))};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(me),t.setAttribute("aria-hidden","true"))}}}var Tr=[159,119,164];function ut(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 ct=new WeakMap;function Cr(n,e){let t=ct.get(n);if(t||(t={button:Jn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),ct.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=dt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Vt(n){let e=ct.get(n);e&&(e.controller?.destroy(),ct.delete(n))}function pt(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){Ht(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 E=y.querySelector(".magicx-aia-pill-scroll");E||(E=document.createElement("span"),E.className="magicx-aia-pill-scroll",E.setAttribute("data-aia-pill-scroll",""),y.insertBefore(E,y.firstChild)),rt(E,a?s:[],0,u,!0,o&&a,l),Or(y,S,o||e.skipDisabled,s[0],m)}else y&&y.remove();let w=e.suggestions[0],T=w?`${w.type} ${w.text}`:"",N=P(e.formatType),F=N&&!o;zn(f,N?[]:t,i,c,d,e.listboxId,o,T,e.optionsPosition??"below",e.showOptionIcons??!0),Cr(n,f.querySelector(".aia-grid")),Wn(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 O=f.querySelector(".magicx-aia-skeleton-bars");if(o&&(!b||N)){if(!O){O=document.createElement("div"),O.className="magicx-aia-skeleton-bars",O.setAttribute("data-aia-skeleton-bars","");for(let E of Tr){let L=document.createElement("span");L.className="magicx-aia-skeleton-bar",L.style.width=`${E}px`,O.appendChild(L)}f.appendChild(O)}}else O&&O.remove();qn(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Ht(n,!0);let C=f.querySelector(".magicx-aia-footer")??Dr(),St=i>=0&&!!t[i]?.is_tappable;Ir(C,tt(St,e.isInputEmpty)),C.isConnected||f.appendChild(C),Ar(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Ar(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 Or(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 Ir(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 Dr(){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=et(),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 ei(n,e){let t=ut(e.listboxId);return n.appendChild(t),{dropdown:t}}function Kt(n,e,t){let i=ne(e);pt(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:H(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 Rr=6,Mr=.3;function ti(n){return n<=0?"0px":`${(-Math.min(Mr,2*Rr/n)).toFixed(3)}px`}function mt(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",Nn(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?M(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=R(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=ti(p.value.length);let w=a&&p.param.icon_svg?ie(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=ti(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&&I(e,Math.max(0,Math.min(g,v)))}var Lr='<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 ni(){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=Lr,n}function kr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ii(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 ri(n,e){let{listboxId:t}=e,i=ut(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",kr()?"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=ni(),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=ce(s),S=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(S)},b=()=>{let p=_(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&&Tn(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(M(s)))},{signal:u}),R(s).addEventListener("selectionchange",()=>{let p=_(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(M(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=R(s),x=_(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($(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=R(s),f=_(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(()=>ii(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 Ut(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(mt({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?rt(r,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):Ft(r)}else Ft(r);ii(i,r),g?(i.focus(),I(i,e.caretOffset??e.text.length)):e.isFocused&&ce(i)!==e.text&&I(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:H(e.editingIdentified.type),required:!0,options:[]}:null,b=h??e.actionableSuggestions[0],v=ne(e);pt(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 oi(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=un(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 ft(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 si(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 Qt=new WeakSet,ai=new WeakMap;function di(n){return n.nodeType===Node.DOCUMENT_NODE}function _r(n){return di(n)?n:n.ownerDocument}function Nr(n){let e=ai.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(ui),ai.set(n,i),i)}catch{return null}}function li(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ui,e.appendChild(t)}function ci(n){if(typeof document>"u")return;let e=n??document;if(Qt.has(e))return;let t=_r(e);if(di(e)){let o=e.head??e.documentElement;if(!o)return;li(t,o),Qt.add(e);return}let i=Nr(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):li(t,e),Qt.add(e)}var ui=`.aia-stack {
1
+ "use strict";var xt=Object.defineProperty;var yi=Object.getOwnPropertyDescriptor;var Si=Object.getOwnPropertyNames;var xi=Object.prototype.hasOwnProperty;var vi=(n,e)=>{for(var t in e)xt(n,t,{get:e[t],enumerable:!0})},Pi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Si(e))!xi.call(n,r)&&r!==t&&xt(n,r,{get:()=>e[r],enumerable:!(i=yi(e,r))||i.enumerable});return n};var Ei=n=>Pi(xt({},"__esModule",{value:!0}),n);var Qr={};vi(Qr,{AIAutocomplete:()=>yt,ATTRIBUTION_URL:()=>Nt,DATE_RANGE_META_END:()=>Pe,DATE_RANGE_META_START:()=>ve,ModeController:()=>re,OPTIONS_GRID_MOBILE_QUERY:()=>ue,OPTION_ENTER_DELAY_VAR:()=>ot,OPTION_ENTER_FADE_MS:()=>Kn,OPTION_ENTER_RISE_MS:()=>Qn,OPTION_ENTER_RISE_PX:()=>Yn,OPTION_ENTER_STAGGER_MS:()=>Un,PLACEHOLDER_FADE_OUT_MS:()=>Ln,PLACEHOLDER_LEAVING_ATTR:()=>Y,PLACEHOLDER_SWAP_GAP_MS:()=>kn,PLACEHOLDER_TYPE_MS:()=>Rn,PLACEHOLDER_WORD_PAUSE_MS:()=>Mn,PRODUCT_PATH_PREFIX:()=>Mt,RANGE_SEPARATOR:()=>Ct,SCROLL_ARROW_ATTR:()=>Wt,SCROLL_ARROW_BOTTOM_VAR:()=>$t,SCROLL_ARROW_CLASS:()=>Bt,SCROLL_ARROW_FADE_MS:()=>Jn,SCROLL_ARROW_LABEL:()=>qt,SCROLL_ARROW_SCROLL_IDLE_MS:()=>Gt,SCROLL_ARROW_VISIBLE_ATTR:()=>me,SKIPPED_PARAM_TEXT:()=>Ot,WEEKDAY_LABELS:()=>se,addMonths:()=>ge,attachScrollArrow:()=>dt,buildAttributionUrl:()=>et,buildDateOptions:()=>he,buildQuery:()=>A,buildSubmitResult:()=>$,cellDay:()=>ye,cellIso:()=>k,computeOptionsGridLayout:()=>_t,createStore:()=>ft,cursorIsAtEnd:()=>He,dateCellMarks:()=>it,dateSelectionFor:()=>ne,extractPlainText:()=>ce,formatAbsoluteDate:()=>V,formatDate:()=>Et,formatDateRange:()=>At,getCursorOffset:()=>M,getFooterHint:()=>tt,identifiedParamLabel:()=>H,isCalendarFormat:()=>P,isOptionsGridMobileViewport:()=>je,isoDate:()=>D,measureOptionsGrid:()=>Ye,monthLabel:()=>fe,needsOptionsGridMeasurement:()=>Ke,optionEnterDelayMs:()=>st,optionLabel:()=>lt,optionsEntranceDurationMs:()=>at,optionsGridTemplateColumns:()=>Ue,parseDate:()=>ae,parseLooseDate:()=>B,parseLooseDateRange:()=>U,plainTextLength:()=>Fe,planOptionsGrid:()=>Qe,previousGraphemeBoundary:()=>Be,productFromMatchedItem:()=>Lt,productsFromCustomFields:()=>qe,renderEditableContent:()=>mt,resolveFormatType:()=>W,resolveIdentifiedDate:()=>xe,sanitizeOptionIconSvg:()=>ie,scrollCaretIntoView:()=>ke,selectedIsoFromText:()=>be,selectedRangeFor:()=>z,setCursorOffset:()=>I,toWireIdentifiedParams:()=>X,visibleDateRange:()=>nt,withSkippedParams:()=>J});module.exports=Ei(Qr);function vt(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function H(n){let e=vt(n);return e.length>0?e.join(" "):n}var j=["January","February","March","April","May","June","July","August","September","October","November","December"],se=["S","M","T","W","T","F","S"],Xt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Jt="aiaDate",Zt="aiaDay",jt=n=>String(n).padStart(2,"0");function D(n){return`${n.getFullYear()}-${jt(n.getMonth()+1)}-${jt(n.getDate())}`}function Pt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function wi(n){let e=Pt(n).getTime()-Pt(new Date).getTime();return Math.round(e/864e5)}function Et(n){let e=wi(n);return e>=0&&e<7?Xt[n.getDay()]:V(n)}function V(n){return n.getFullYear()===new Date().getFullYear()?`${j[n.getMonth()]} ${n.getDate()}`:`${j[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ae(n){if(!n)return null;let e=Xt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Pt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=j.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 fe(n){return`${j[n.month]} ${n.year}`}function wt(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function en(n){return{year:n.getFullYear(),month:n.getMonth()}}function ge(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function zt(){return{text:"",is_tappable:!1,kind:null}}function he(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(zt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Et(o),is_tappable:!0,kind:null,metadata:{[Jt]:D(o),[Zt]:r}})}for(;i.length%se.length!==0;)i.push(zt());return i}function be(n){let e=ae(n);return e?D(e):null}function k(n){let e=n?.metadata?.[Jt];return typeof e=="string"?e:null}function ye(n){let e=n?.metadata?.[Zt];return typeof e=="number"?e:null}function Ti(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function tn(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:j.findIndex(t=>t.toLowerCase().startsWith(e))}function Ci(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 nn(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function B(n,e={}){if(!n)return null;let t=e.today??new Date,i=Ti(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=nn(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?D(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=tn(o[1]);if(l>=0)return Se(l,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=tn(s[2]);if(l>=0)return Se(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?Se(c-1,l,a[3],t):c>12&&l<=12?Se(l-1,c,a[3],t):null}return null}function Se(n,e,t,i){if(t){if(t.length!==4)return null;let o=nn(Number(t),n,e);return o?D(o):null}let r=Ci(n,e,i);return r?D(r):null}function xe(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:B(n.text,e)}var Ct=" - ",ve="aiaDateRangeStart",Pe="aiaDateRangeEnd";function le(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Tt=/^\d{4}-\d{2}-\d{2}$/;function rn(n){if(!Tt.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 Ai=/\s+(?:to|through|thru|until|til|till)\s+/g,Oi=/[-–—]/g;function Ii(n){let e=[];for(let t of[Ai,Oi]){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 U(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[r,o]of Ii(n.trim())){let s=B(r.trim(),e);if(!s)continue;let a=B(o.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function At(n){let e=rn(n.start),t=rn(n.end);return!e||!t?"":n.start===n.end?V(e):`${V(e)}${Ct}${V(t)}`}function on(n,e){let t=le(n,e);return{text:At(t),is_tappable:!0,kind:null,metadata:{[ve]:t.start,[Pe]:t.end}}}function z(n,e={}){let t=n?.metadata?.[ve],i=n?.metadata?.[Pe];return typeof t=="string"&&typeof i=="string"&&Tt.test(t)&&Tt.test(i)?le(t,i):U(n?.text,e)}function P(n){return n==="date"||n==="date-range"}var Di=new Set(["date","dates"]),Ri=new Set(["range","ranges","span","period","window"]),sn=3;function Mi(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(U(t.text)!==null?e.range+=1:B(t.text)!==null&&(e.single+=1));return e}function W(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Mi(n.options);if(t.single+t.range>=sn&&t.range>t.single)return"date-range";let i=vt(n.type);return i.some(r=>Di.has(r))?i.some(r=>Ri.has(r))?"date-range":"date":t.single>=sn?"date":"options"}var Ee=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var Li="https://api.ai-autocomplete.com",we=`${Li}/api/suggest`,an=new WeakMap;function de(n){return n?.type==="accessToken"}function ki(n){if(!(!n||de(n)))return n}function Te(n){let e=an.get(n.getAccessToken);return e||(e=new Ee(n),an.set(n.getAccessToken,e)),e}function Ce(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ae(n){let e=ki(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function X(n){return n.map(e=>({type:e.type,value:e.text}))}var Ot="skipped";function J(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:Ot,kind:null}));return i.length>0?[...n,...i]:n}var _i="0.24.0",ln=!1;function Ni(){return crypto.randomUUID()}function Fi(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Hi(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:J(e.map(d=>Fi(d,t)),s??[]),...r&&r.length>0&&{identified_params:X(r)},...o&&o.length>0&&{recently_suggested:o},...c!=null&&{contact_account_count:c},...a!==void 0&&{additional_context:a}},meta:{request_id:Ni(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:_i,session_id:i}}}async function dn(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function cn(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=Hi(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Ce(i),a=i?.endpoint??we,l=JSON.stringify(o);if(de(i)){let u=Te(i),f=await u.getToken(),g=await dn(a,s,f,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await dn(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=Ae(i);!c&&!ln&&(ln=!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 A(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(y=>h<y.end&&h+a.text.length>y.start);)h=t.indexOf(a.text,h+1);return h},f=u(s);if(f===-1&&(f=u(0)),f!==-1){t=t.slice(0,f)+d+t.slice(f+a.text.length);let g=d.length-a.text.length;for(let h of o)h.start>=f+a.text.length&&(h.start+=g,h.end+=g);o.push({start:f,end:f+d.length}),s=f>=s?f+d.length:s+g}r.push({...a,placeholder:d})}return{rawQuery:t,completedParams:r}}function G(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Oe(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function K(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 un(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 Q(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 Z(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 pn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function mn(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 fn(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 gn(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 hn(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 It(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 bn(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 yn(n,e,t=[]){let i=It(n,e).located,r=bn(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 Sn(n,e){let{located:t,missing:i}=It(n,e);return{valid:t.map(r=>r.param),invalid:i}}function Ie(n,e,t){let i=It(n,e).located,{located:r,missing:o}=bn(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function Bi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Wi=100,Gi=300,$i=2,De=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?gn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await cn(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(S=>S.source==="identified").map(S=>({id:crypto.randomUUID(),type:S.type,text:S.text})),d=pn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],f=u[u.length-1],g=this.store.get().text,h,y;if(f?.state==="in_progress"){y=!0;let S=g.toLowerCase().lastIndexOf(f.text.toLowerCase());h=S!==-1?S:o}else y=!1,h=o;let p=d.filter(S=>S.type!=="placeholder")[0],m=null;if(p&&!P(W(p))){let S=K(g,h,y),w=Z(p.options,S);w&&(m={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 b=l.data.custom_fields??null,x=this.callbacks.productsForResponse?.(b);this.store.set(S=>{let w=m?[...S.completedParams,m]:S.completedParams,T=Ie(S.text,w,c).valid,N=new Set(s.skippedParams.map(C=>C.id)),F=new Set(S.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:y,identifiedParams:T,customFields:b,...x!==void 0?{products:x}:{},...m?{completedParams:w}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=Bi(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($i)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Wi),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),Gi)}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=G(i.text,i.filterBase,o),a=K(i.text,s,i.filterInProgress),c=i.suggestions.filter(x=>x.type!=="placeholder")[0],d=P(i.activeFormatType),f=(c&&!d?Q(c.options,a):[]).filter(x=>x.is_tappable),g=c&&!d?Z(c.options,a)!==null:!1,h=a.trim().length>0;if(f.length>0&&!g&&h||Oe(i.text,i.completedParams.length,o))return!1;let{rawQuery:y,completedParams:v}=A(i.text,i.completedParams),p=y.length<i.lastRawQuery.length,m=Math.abs(y.length-i.lastRawQuery.length),b=t&&y!==i.lastRawQuery;return p||m>=e||b?(this.doFetch(y,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function qi(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function Re(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&qi(e)?e:n.ownerDocument??n}function R(n){return n.ownerDocument??n}function _(n){let t=Re(n).getSelection?.();return t||(R(n).getSelection?.()??null)}function Me(n,e){let t=n?Re(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Le=2,Vi="magicx-aia";function xn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Ui(n){let e=R(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&&xn(s.overflowX)||o&&xn(s.overflowY))return i}if(i.classList.contains(Vi))return null;i=i.parentElement}return null}function ke(n){let e=_(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=Ui(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+Le:r.left<s&&(i.scrollLeft-=s-r.left+Le)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+Le:r.top<s&&(i.scrollTop-=s-r.top+Le)}}var En='[contenteditable="false"]',Ki="strong[data-param-id]",ee;function Qi(){if(ee!==void 0)return ee;let n=globalThis.Intl.Segmenter;if(!n)return ee=null,null;try{ee=new n(void 0,{granularity:"grapheme"})}catch{ee=null}return ee??null}function _e(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(En))return!0;t=t.parentNode}return!1}function Ne(n){return R(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return _e(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ce(n){let e=Ne(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Fe(n){let e=Ne(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function M(n){let e=_(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(_e(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=wn(r.childNodes[s],n);return o+vn(r,n)}return t.nodeType!==Node.TEXT_NODE||_e(t,n)?null:vn(t,n)+i}function wn(n,e){if(n.nodeType===Node.TEXT_NODE)return _e(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(En))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=wn(r,e);return i}function vn(n,e){let t=Ne(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 I(n,e){let t=R(n),i=_(n);if(!i)return;let r=Math.max(0,Math.min(e,Fe(n))),o=Ne(n),s=0,a=null,l=0,c=o.nextNode(),d=null;for(;c;){let f=c.data.length;if(r<s+f){a=c,l=r-s;break}if(r===s+f){let g=o.nextNode();g?(a=g,l=0):(a=c,l=f);break}s+=f,d=c,c=o.nextNode()}let u=t.createRange();if(a){let f=a.parentElement?.closest('strong[data-seg="completed"]');f&&f!==n&&n.contains(f)?l===0?u.setStartBefore(f):l===a.data.length?u.setStartAfter(f):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),Yi(n,i,u,r),ke(n)}function Pn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Ki)??null;return i&&e.contains(i)?i:null}function Yi(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 Tn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=M(n);return i!==null&&t===`${i}:${e}`}function He(n){let e=M(n);return e==null?!1:e>=Fe(n)}function Be(n,e){if(e<=0)return 0;let t=Qi();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 $(n,e,t=[],i={}){let{rawQuery:r,completedParams:o}=A(n,e);return{query:n.trim(),raw_query:r,completed_params:J(o,t),identified_params:X(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Dt(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")?He(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Rt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?M(n):null}var We=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=Dt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=P(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(P(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 f=l.indexOf(t.activeDropdownIndex),g=f<l.length-1?f+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let f=Dt(e.target,t),g=!!t.editingParam;if(!f&&!g)break;e.preventDefault();let h=P(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(),P(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(),P(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let f=t.activeDropdownIndex+1;f<t.filteredOptions.length&&t.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,f=t.editingTail;this.ctx.exitEditMode?.(),I(u,f);break}Dt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%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=Rt(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?.(),I(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=Rt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Rt(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($(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),f;if(u<0)f=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;f=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[f]});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?.(),I(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=D(new Date),r=e.filteredOptions.findIndex(s=>k(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=Me(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=Me(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=Me(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Ge=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(P(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||ji(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 ji(n){return n instanceof Error&&n.name==="AbortError"}var $e=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}=A(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 Mt="/products/",Cn="https://relative.invalid";function zi(n){if(!n)return;let e;try{e=new URL(n,`${Cn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Cn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Lt(n){let e=zi(n.item_url)??(n.handle?`${Mt}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function qe(n){return(n?.items.matched??[]).map(Lt)}var Ve=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 qe(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||Xi(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 Xi(n){return n instanceof Error&&n.name==="AbortError"}var ue="(max-width: 768px)";var Ji="var(--aia-option-row-height, 37px)",Zi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function _t(n,e){return e?kt(1,Math.min(n,5)):kt(1,Math.min(n,4))}function kt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Ji} + ${Zi})`}}function Ke(n,e){return!e&&n>=5}function Qe(n,e,t,i){if(!(!e&&n>=5&&er(t,i))){let s=_t(n,e);return{...s,template:Ue(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let o=6;return{...kt(2,3),template:Ue(2),scrollHintIndices:n>o?[o-2,o-1]:[]}}function er(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 Ye(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 Ue(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function je(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(ue).matches}function An(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 pe(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 On(n){if(!n)return wt();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function tr(n){let e=ae(n);return e?en(e):wt()}function In(n,e){let t=yn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(E=>E.type!=="placeholder"),r=i[0],o=n.suggestions.filter(E=>E.type==="placeholder").map(E=>E.text).join(" "),s=G(n.text,Math.min(n.filterBase,n.text.length),o),l=s===0&&Oe(n.text,n.completedParams.length,o)?"":K(n.text,s,n.filterInProgress),c=r?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,f,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let E=n.editingParam.id,L=n.completedParams.some(bi=>bi.id===E),oe=n.caretOffset??n.editingAnchor,Yt=L?"":n.text.slice(n.editingAnchor,oe);f=Yt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=Q(n.editingParam.options,Yt)}else f=l.trim(),g=c,h=r?.type,u=Q(c,l);let y=n.optionSearch,v=y!=null&&h!=null&&y.type===h;v&&y.status==="done"&&y.query===f&&(u=g);let p=v&&y.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(E=>E.is_tappable));let b=n.editingIdentified,x=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,S=b?b.format:W(x),w=d&&P(S)?z(n.editingParam):null;w&&(S="date-range");let T=null,N=null;if(P(S)){let E=pe({...n,actionableSuggestions:i}),L=n.dateViewMonth;T=L&&L.key===E?{year:L.year,month:L.month}:b?On(b.iso):w?On(w.start):tr(n.editingParam?.text),u=he(T);let oe=n.pendingRangeStart;S==="date-range"&&oe&&oe.key===E&&(N=oe.iso)}let F=E=>m?E.is_tappable:!0,O;if(d){let E=n.editingParam?.options??[];O=n.editingParam!=null&&E.filter(F).length===0}else O=r!=null&&c.filter(F).length===0;let C=An({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:O,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),St=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:S,dateView:T,dateRangeStart:N,placeholderText:o,optionQuery:f,isSearchingOptions:p,isDropdownOpen:C,isActivePillSelected:St}}function ze(n){return n.mode==="fresh"?nr(n):ir(n)}function nr(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=G(e,r,l),d=K(e,c,o),u=Z(a.options,d);if(!u)return null;let f=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(f),h=g>=0?g:Math.max(0,e.length-u.text.length),y=h+u.text.length,v=e.slice(h,y),m=y<e.length&&e[y]===" "?y+1:y,b={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,b],suggestions:i.filter(x=>x!==a),filterBase:m,newParamId:b.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function ir(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(b=>b.id===i.id))return null;let s=e.slice(r,o),a=Z(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,f=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:f,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 b=0;b<t.length;b++){let x=e.indexOf(t[b].text,p);if(x!==-1){if(x>=g){v=b;break}p=x+t[b].text.length}}let m=[...t];return m.splice(v,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Xe(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 Je=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===""?Xe(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:A(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,f=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),y=t.completedParams.filter(p=>p.id!==i.id),v=h>=0?Math.min(h,y.length):y.length;y.splice(v,0,g),this.deps.store.set({text:u,completedParams:y,newParamId:g.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(f),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=ze({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 Rn=33,Mn=70,Ln=120,kn=50,Y="data-aia-placeholder-leaving",te=new WeakMap;function Ze(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function rr(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function _n(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Nn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(_n(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(()=>Nn(n,e),33+i)}function Dn(n,e){_n(n,e,0),e.timer=setTimeout(()=>Nn(n,e),33)}function Fn(n,e){let t=te.get(n);if(e===""){t&&(Ze(t),te.delete(n)),n.removeAttribute(Y),delete n.dataset.placeholder;return}if(t?.target===e)return;if(rr(n)){t&&Ze(t),n.removeAttribute(Y),te.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&&Ze(t),te.set(n,i),r){n.setAttribute(Y,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(Y),n.isConnected&&Dn(n,i)},170);return}n.removeAttribute(Y),Dn(n,i)}function Hn(n){let e=te.get(n);e&&(Ze(e),te.delete(n))}var Nt="https://ai-autocomplete.com";function et(n=Nt){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 tt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var or={selectedIso:null,selectedRange:null,rangeStart:null};function ne(n){if(!P(n.activeFormatType))return or;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:r}=e;return{selectedIso:r?null:i,selectedRange:i&&r?le(i,r):null,rangeStart:n.dateRangeStart}}let t=z(n.editingParam);return{selectedIso:t?null:be(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function nt(n){return n.pendingStart?le(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function it(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 Bn="data-aia-key";function q(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Bn);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(Bn,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 Gn(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=lr(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=fe(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&&sr(u,e,t,i,o,s)}function sr(n,e,t,i,r,o){let s=D(new Date),a=nt({pendingStart:r.rangeStart,highlightedIso:k(e[t]),selected:r.selectedRange});q(n,e,{keyOf:(l,c)=>k(l)??`pad-${c}`,create:l=>ar(l),update:(l,c,d)=>{let u=k(c),f=it(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",f.selected),l.classList.toggle("magicx-aia-date-cell--in-range",f.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 ar(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=ye(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 lr(){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(Wn("prev","Previous month","\u2039"),t,Wn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of se){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 Wn(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 $n=[125,69];function qn(n,e){return e?1:n===0?.7:n===1?.4:.2}function rt(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<$n.length;l++){let c=$n[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(qn(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();q(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,f=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(qn(d,f)),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 Ft(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var dr="Products";function Vn(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.setAttribute("data-aia-products-label",""),a.textContent=dr;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&&q(s,e,{keyOf:a=>cr(a),create:a=>ur(a,i,r),update:(a,l,c)=>{a.id=`${t}-product-${c}`,a.dataset.aiaIndex=String(c)}})}function Ht(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function cr(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function ur(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 Un=80,Kn=150,Qn=280,Yn=16,ot="--aia-option-enter-delay";function st(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 at(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 jn="http://www.w3.org/2000/svg",pr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function mr(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var fr=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],gr=/^[a-zA-Z0-9#.,%\s()-]+$/;function hr(n){let e=[];for(let t of fr){let i=n.getAttribute(t);i===null||!gr.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function zn(n){for(let e of Array.from(n.attributes))mr(e.name,e.value)&&n.removeAttribute(e.name);hr(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!pr.has(t.localName)||t.namespaceURI!==jn?t.remove():zn(t)}else e.remove()}function ie(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!==jn||e.getElementsByTagName("parsererror").length>0?null:(zn(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function lt(n){return n.text}function br(n,e,t){let i=je(),r=!t&&Ke(e,i)?Ye(n):null,o=Qe(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 Xn(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,yr(d,e,t,i,r,o,s,c);let f=br(d,e.length,s);Sr(d,e.length,f,s,l),u&&(d.scrollTop=0)}function yr(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??"":()=>"";q(n,e,{keyOf:u=>`${u.text}\0${d(u)}\0${l}\0${c}`,create:(u,f)=>{let g=xr(u,s,a);return s||(g.dataset.aiaEntering=""),g},update:(u,f,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&&f.is_tappable?(u.onclick=()=>{u.classList.add("magicx-aia-option--pressed"),i(f),setTimeout(()=>u.classList.remove("magicx-aia-option--pressed"),170)},u.onmouseenter=()=>{let y=Number.parseInt(u.dataset.aiaIndex??"-1",10);y>=0&&r(y)}):(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(ot,`${st(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function xr(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?ie(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=lt(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 Bt="magicx-aia-scroll-arrow",Wt="data-aia-scroll-arrow",me="data-aia-visible",Jn=1e3,Gt=160,$t="--aia-scroll-arrow-bottom",qt="Scroll down for more options",vr="[data-aia-products-label]",Pr=4,Er=8,wr=240;function Tr(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||ei(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)/wr),u=1-(1-d)*(1-d);n.scrollTop=r+e*u,d<1?o.call(t,c):i()};o.call(t,c)}function Cr(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Zn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Bt,e.setAttribute(Wt,""),e.setAttribute("aria-label",qt),e.setAttribute("aria-hidden","true"),e.appendChild(Cr(n)),e}function Ar(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function ei(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function dt({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=p=>{p?(t.setAttribute(me,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(me),t.setAttribute("aria-hidden","true"))},c=p=>{let m=0,b=p;for(;b&&b!==n;)m+=b.offsetTop,b=b.offsetParent instanceof HTMLElement?b.offsetParent:null;return m},d=()=>{let p=n.querySelector(vr),m;if(p){let b=c(p)+p.offsetHeight/2;m=n.clientHeight-b-t.offsetHeight/2}else{let b=c(e),x=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;m=n.clientHeight-(b+e.offsetHeight)+(x>0?0:Er)}t.style.setProperty($t,`${Math.max(0,Math.round(m))}px`)},u=()=>{if(r||s!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;l(!p&&m>Pr)},f=()=>{if(r)return;d();let p=e.getAttribute("data-aia-group")??"";if(p!==o){o=p,l(!1),s!==null&&clearTimeout(s);let m=e.querySelectorAll("[data-aia-option]").length,b=ei(e)?0:at(m,Ar(e));s=setTimeout(()=>{s=null,u()},b);return}u()},g=()=>{r||s!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,u()},Gt))};e.addEventListener("scroll",g,{passive:!0});let h=p=>p.preventDefault(),y=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-p);Tr(e,m,i,g)};t.addEventListener("mousedown",h),t.addEventListener("click",y);let v=null;return i&&typeof i.ResizeObserver=="function"&&(v=new i.ResizeObserver(()=>{d(),u()}),v.observe(e)),f(),{update:f,destroy(){r||(r=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",h),t.removeEventListener("click",y),v?.disconnect(),t.removeAttribute(me),t.setAttribute("aria-hidden","true"))}}}var Or=[159,119,164];function ut(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 ct=new WeakMap;function Ir(n,e){let t=ct.get(n);if(t||(t={button:Zn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),ct.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=dt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Vt(n){let e=ct.get(n);e&&(e.controller?.destroy(),ct.delete(n))}function pt(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:f}=e,g=s.length>0,h=a&&g,y=t.length>0,v=e.products.length>0,p=r&&(y||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){Ht(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let b=e.showSkipButton&&g&&!e.isInputEmpty,x=h||o&&a||b,S=m.querySelector(".magicx-aia-pill-bar");if(x){S||(S=document.createElement("div"),S.className="magicx-aia-pill-bar aia-cluster",S.setAttribute("data-nowrap",""),S.setAttribute("data-aia-pillbar",""),m.insertBefore(S,m.firstChild));let E=S.querySelector(".magicx-aia-pill-scroll");E||(E=document.createElement("span"),E.className="magicx-aia-pill-scroll",E.setAttribute("data-aia-pill-scroll",""),S.insertBefore(E,S.firstChild)),rt(E,a?s:[],0,u,!0,o&&a,l),Rr(S,b,o||e.skipDisabled,s[0],f)}else S&&S.remove();let w=e.suggestions[0],T=w?`${w.type} ${w.text}`:"",N=P(e.formatType),F=N&&!o;Xn(m,N?[]:t,i,c,d,e.listboxId,o,T,e.optionsPosition??"below",e.showOptionIcons??!0),Ir(n,m.querySelector(".aia-grid")),Gn(m,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 O=m.querySelector(".magicx-aia-skeleton-bars");if(o&&(!y||N)){if(!O){O=document.createElement("div"),O.className="magicx-aia-skeleton-bars",O.setAttribute("data-aia-skeleton-bars","");for(let E of Or){let L=document.createElement("span");L.className="magicx-aia-skeleton-bar",L.style.width=`${E}px`,O.appendChild(L)}m.appendChild(O)}}else O&&O.remove();Vn(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Ht(n,!0);let C=m.querySelector(".magicx-aia-footer")??Lr(),St=i>=0&&!!t[i]?.is_tappable;Mr(C,tt(St,e.isInputEmpty)),C.isConnected||m.appendChild(C),Dr(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Dr(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 Rr(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 Mr(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 Lr(){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=et(),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 ti(n,e){let t=ut(e.listboxId);return n.appendChild(t),{dropdown:t}}function Ut(n,e,t){let i=ne(e);pt(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:H(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 kr=6,_r=.3;function ni(n){return n<=0?"0px":`${(-Math.min(_r,2*kr/n)).toFixed(3)}px`}function mt(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",Fn(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??"",f=e.dataset.editingParamId??"";if(c===d&&(i??"")===u&&(r??"")===f)return;let g=s?M(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=R(e),y=h.createDocumentFragment(),v=0;for(let p of t)if(v+=p.value.length,p.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=p.param.id;let b=p.param.id===i,x=p.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];b&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),m.className=S.join(" "),m.style.letterSpacing=ni(p.value.length);let w=a&&p.param.icon_svg?ie(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,m.appendChild(T),p.param.icon&&(m.dataset.aiaIcon=p.param.icon)}m.appendChild(h.createTextNode(p.value)),y.appendChild(m)}else if(p.type==="identified"){let m=h.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=p.param.id;let b=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===r&&b.push("magicx-aia-segment--editing"),m.className=b.join(" "),m.style.letterSpacing=ni(p.value.length),m.textContent=p.value,y.appendChild(m)}else y.appendChild(h.createTextNode(p.value));e.replaceChildren(y),e.dataset.aiaTextLength=String(v),g!=null&&I(e,Math.max(0,Math.min(g,v)))}var Nr='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function ii(){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=Nr,n}function Fr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ri(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 oi(n,e){let{listboxId:t}=e,i=ut(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",Fr()?"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=ii(),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,f=!1,g=0,h=()=>{let p=ce(s),b=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(b)},y=()=>{let p=_(s);if(!p||p.rangeCount===0)return null;let m=p.anchorNode;if(!m||!s.contains(m))return null;let S=(m.nodeType===Node.ELEMENT_NODE?m:m.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return S&&Tn(s,S)?null:S};if(r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{f||(g=performance.now(),h(),e.handleCaretAfterInput(M(s)))},{signal:u}),R(s).addEventListener("selectionchange",()=>{let p=_(s);if(!p||p.rangeCount===0||!s.contains(p.anchorNode))return;let m=p.isCollapsed?y():null,b=e.store.get(),x=b.editingParam?.id??b.editingIdentified?.id??null;if(m&&m!==x){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(M(s))},{signal:u}),s.addEventListener("compositionstart",()=>{f=!0},{signal:u}),s.addEventListener("compositionend",()=>{f=!1,h()},{signal:u}),s.addEventListener("beforeinput",p=>{let m=p,b=m.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){p.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let x=b.startsWith("delete")?"":m.data??"";e.replaceEditingRange(x)&&p.preventDefault()}},{signal:u}),s.addEventListener("paste",p=>{p.preventDefault();let m=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let b=R(s),x=_(s);if(!x||x.rangeCount===0)return;let S=x.getRangeAt(0);if(!s.contains(S.startContainer))return;S.deleteContents();let w=b.createTextNode(m);S.insertNode(w),S.setStartAfter(w),S.collapse(!0),x.removeAllRanges(),x.addRange(S),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 m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit($(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let p=R(s),m=_(s),b=m&&m.rangeCount>0&&s.contains(m.anchorNode);if(m&&!b){let x=p.createRange();x.selectNodeContents(s),x.collapse(!0),m.removeAllRanges(),m.addRange(x)}}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>ri(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 Kt(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 f=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==f;if(mt({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?rt(r,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):Ft(r)}else Ft(r);ri(i,r),g?(i.focus(),I(i,e.caretOffset??e.text.length)):e.isFocused&&ce(i)!==e.text&&I(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:H(e.editingIdentified.type),required:!0,options:[]}:null,y=h??e.actionableSuggestions[0],v=ne(e);pt(o,{suggestions:y?[{...y,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 si(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=un(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()),f=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:f,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(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:h}}function ft(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 f of t)f(d,u)}}catch(l){throw i.length=0,l}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function ai(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 Qt=new WeakSet,li=new WeakMap;function ci(n){return n.nodeType===Node.DOCUMENT_NODE}function Hr(n){return ci(n)?n:n.ownerDocument}function Br(n){let e=li.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(pi),li.set(n,i),i)}catch{return null}}function di(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=pi,e.appendChild(t)}function ui(n){if(typeof document>"u")return;let e=n??document;if(Qt.has(e))return;let t=Hr(e);if(ci(e)){let o=e.head??e.documentElement;if(!o)return;di(t,o),Qt.add(e);return}let i=Br(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):di(t,e),Qt.add(e)}var pi=`.aia-stack {
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--aia-stack-space, 0.5rem);
@@ -101,7 +101,14 @@
101
101
 
102
102
  /* --- Input wrapper --- */
103
103
  .magicx-aia-input-wrapper {
104
- padding: 12px 16px;
104
+ /* The left inset is a token shared with the dropdown (which insets its
105
+ content by the same amount), so the typed text, the parameter label,
106
+ the option text and the product strip share one left edge. A host that
107
+ pads the field to clear its own leading icon sets --aia-content-inset-left
108
+ and the dropdown follows. Floored at 10px \u2014 the dropdown's sections inset
109
+ their text by 10px and its own padding can't go below zero, so below
110
+ 10px the two sides would diverge; flooring both keeps them together. */
111
+ padding: 12px 16px 12px max(10px, var(--aia-content-inset-left, 16px));
105
112
  border: 1px solid var(--aia-border, #b0b0b0);
106
113
  border-radius: 20px;
107
114
  background: var(--aia-surface, #ffffff);
@@ -326,6 +333,10 @@
326
333
  width: 18px;
327
334
  height: 18px;
328
335
  fill: none;
336
+ /* The root draws nothing and the path pins its own stroke, but a page's
337
+ \`svg { stroke: \u2026 }\` would otherwise still land here; say none, as the
338
+ markup does. */
339
+ stroke: none;
329
340
  }
330
341
  .magicx-aia-submit svg path {
331
342
  fill: none;
@@ -364,7 +375,15 @@
364
375
  display: flex;
365
376
  flex-direction: column;
366
377
  box-sizing: border-box;
367
- padding: 10px 8px;
378
+ /* The left padding derives from --aia-content-inset-left, the token the
379
+ input wrapper reads for its own left padding. The option text and the
380
+ parameter label sit 10px inside this padding edge (the option's padding;
381
+ the pill bar's list wrapper carries the same 10px \u2014 see appearance.css),
382
+ and the product strip is inset to the same line, so the whole panel's
383
+ content starts exactly under the typed text. max() keeps the padding at
384
+ zero (never negative, which CSS would clamp anyway) for a token under
385
+ 10px \u2014 the input wrapper floors the token at 10px to match. */
386
+ padding: 10px 8px 10px max(0px, calc(var(--aia-content-inset-left, 16px) - 10px));
368
387
  overflow: hidden;
369
388
  container-type: inline-size;
370
389
  z-index: 10;
@@ -542,9 +561,11 @@
542
561
  display: flex;
543
562
  flex-direction: column;
544
563
  gap: 6px;
545
- /* Matches the grid's own 8px inline padding so the section label lines up
546
- with the option text above it. */
547
- padding: 0 8px;
564
+ /* The option text sits 10px inside the dropdown's padding edge (the
565
+ option's own padding), so the section carries the same 10px and its
566
+ label lands on the option text's left edge \u2014 which the dropdown in turn
567
+ places under the typed text (--aia-content-inset-left). */
568
+ padding: 0 10px;
548
569
  min-width: 0;
549
570
  }
550
571
 
@@ -572,6 +593,10 @@
572
593
  overflow-y: hidden;
573
594
  overscroll-behavior-x: contain;
574
595
  padding-bottom: 2px;
596
+ /* Pull the row out by the card's own 6px padding so the first card's
597
+ image tile \u2014 not its hover fill \u2014 starts on the label's left edge, the
598
+ same way the option's highlight fill hangs outside its text. */
599
+ margin-inline: -6px;
575
600
  /* Hide the scrollbar chrome across all three engines while leaving the box
576
601
  scrollable by trackpad, wheel, touch and keyboard. Firefox + the old Edge
577
602
  property first, WebKit/Blink via the pseudo-element below. */
@@ -707,9 +732,10 @@
707
732
  /* --- "More below" scroll arrow (see render/scrollArrow.ts) ---
708
733
  A bare down chevron at the bottom-centre of the option list, shown while
709
734
  there is more to scroll to \u2014 no disc, border or shadow around it. It rests
710
- just above the grid's reserved band (--aia-scroll-arrow-bottom is measured
711
- and set inline by the controller so it tracks the grid's bottom edge in
712
- every layout). It never travels with the scroll: the controller toggles
735
+ just above the grid's reserved band, or \u2014 when a product strip follows the
736
+ grid \u2014 centred on the strip's "Products" label row, off the last option row
737
+ (--aia-scroll-arrow-bottom is measured and set inline by the controller so
738
+ it tracks the layout). It never travels with the scroll: the controller toggles
713
739
  data-aia-visible and the only thing that transitions is opacity \u2014 a slow,
714
740
  even second in and the same second out. Its one motion is an idle bob, a few
715
741
  pixels up and back over a couple of seconds, running all the time so a fade
@@ -1094,7 +1120,17 @@
1094
1120
  /* --- Option item --- */
1095
1121
  .magicx-aia-option {
1096
1122
  position: relative;
1097
- overflow: visible;
1123
+ /* Clip, not visible: the entrance rise below runs on the inner content,
1124
+ and a transformed box extends its scroll container's scrollable area.
1125
+ Unclipped, the rows rising 16px from below made the option grid overflow
1126
+ for the length of the entrance whenever nothing sat under the grid to
1127
+ absorb it (product strip, optionsPosition="above"), so a scrollbar
1128
+ flashed in and out and the columns shifted sideways by its width. The
1129
+ cell's own children never paint outside it (the streak layer clips
1130
+ itself; press and highlight stay inside the box), so nothing is lost.
1131
+ \`hidden\` first for engines without \`clip\`. */
1132
+ overflow: hidden;
1133
+ overflow: clip;
1098
1134
  display: flex;
1099
1135
  /* Top-align so single-line and multi-line options in the same row share
1100
1136
  the same baseline at the top edge of the cell. */
@@ -1112,11 +1148,10 @@
1112
1148
  padding: 8px 10px;
1113
1149
  /* Entrance: fade in while rising into place, each row a beat after the one
1114
1150
  before it (--aia-option-enter-delay is set inline per row from the core's
1115
- optionEnterDelayMs). The durations and distance mirror OPTION_ENTER_* in
1116
- derive/optionsEntrance.ts \u2014 change both together. */
1117
- animation:
1118
- magicx-aia-optionFadeIn 150ms ease-out both,
1119
- magicx-aia-optionRiseIn 280ms cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
1151
+ optionEnterDelayMs). The fade is here; the rise is on the inner content
1152
+ (see the overflow note above). The durations and distance mirror
1153
+ OPTION_ENTER_* in derive/optionsEntrance.ts \u2014 change both together. */
1154
+ animation: magicx-aia-optionFadeIn 150ms ease-out both;
1120
1155
  animation-delay: var(--aia-option-enter-delay, 0ms);
1121
1156
  }
1122
1157
 
@@ -1135,6 +1170,10 @@
1135
1170
  .magicx-aia-option-content {
1136
1171
  position: relative;
1137
1172
  z-index: 2;
1173
+ /* The entrance rise (the cell above keeps the fade). Inherits the cell's
1174
+ per-row delay through the custom property. */
1175
+ animation: magicx-aia-optionRiseIn 280ms cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
1176
+ animation-delay: var(--aia-option-enter-delay, 0ms);
1138
1177
  }
1139
1178
 
1140
1179
  .magicx-aia-option--tappable {
@@ -1377,6 +1416,7 @@
1377
1416
  rest of the SDK's motion is left as-is \u2014 it predates this block. */
1378
1417
  @media (prefers-reduced-motion: reduce) {
1379
1418
  .magicx-aia-option,
1419
+ .magicx-aia-option-content,
1380
1420
  .magicx-aia-scroll-arrow,
1381
1421
  .magicx-aia-dropdown,
1382
1422
  .magicx-aia-input[data-aia-empty="true"][data-placeholder]::before {
@@ -1832,5 +1872,5 @@
1832
1872
  background: var(--aia-surface, #ffffff);
1833
1873
  }
1834
1874
  }
1835
- `;var gt=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(r){return this.report(e,r,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var ht=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...s)=>t(...s);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var bt=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var re=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Fr(n){return(n??we).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Hr(n){return de(n)?`Bearer ${await Te(n).getToken()}`:Ae(n)}async function pi(n){try{let e=Fr(n.apiConfig?.endpoint),t=Ce(n.apiConfig),i=await Hr(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var Br="newParam",mi="suggestionRemoval",Wr="selectionAnimation",Gr=650,$r=0;function qr(){return`:ac-${++$r}:`}var fi=170;function gi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var yt=class{constructor(e,t={}){this.inputStore=ft(gi());this._listboxId=qr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new bt;this.boundary=new gt;this.subscriberCount=0;this.emitter=new ht(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=si(this.inputStore,i=>On(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new $e(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Je({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Ve(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Ge(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,r)=>{i==="pill"&&r.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new De(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,r)=>this.optionSource.tick(i,r)}),this.keyboardController=new We(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:s}=Ie(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.identifiedParams===r.identifiedParams)return;let o=i.editingIdentified;if(!o||i.identifiedParams.some(l=>l.id===o.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===o.anchor&&l.value===o.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...o,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let r=i.pendingRangeStart;!r||r.key===pe(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let s=o.anchor;if(i.text!==r.text){let l=hn(r.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||fn(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(ci(this.opts.styleRoot??Re(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...gi(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.optionSource.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(Fn(this.domRefs.input),Vt(this.domRefs.dropdown)),this.dropdownRefs&&Vt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:l,removed:c}=Xe(i,r,o);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>r?Math.max(r,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let s=Be(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),I(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let r=W(i);if(!P(r))return!1;let o=K(i.text),s=r==="date-range"||o?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:o?o.start:xe(i),isoEnd:o?o.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!P(t.activeFormatType)||!t.dateView)return;let i=ge(t.dateView,e);this.store.set({dateViewMonth:{...i,key:pe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return $(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.showProducts,r=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==r&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showChipIcons!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.activeFormatType==="date-range"){let r=k(e);if(r){let o=t.dateRangeStart;if(!o){this.store.set({pendingRangeStart:{iso:r,key:pe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(on(o,r));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=oi(t,e);if(i){if(this.fireTelemetry("option",{raw_query:A(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(mi),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(mi,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},fi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Wr,()=>this.store.set({inSelectionAnimation:!1}),fi)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");pi({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new re(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showChipIcons(){return e.opts.showChipIcons??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=ri(this.container,t);let i=()=>{this.domRefs&&Ut(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Ut(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=ei(this.container,t);let i=()=>{this.dropdownRefs&&Kt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Kt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(ue),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Br,()=>this.store.set({newParamId:null}),Gr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Sn(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=G(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=mn(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);Q(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=A(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let r=t.text.slice(0,i.anchor),o=t.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=o.length===0||o[0]!==" "?`${s} `:s,c=r+l+o,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:H(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg};this.fireTelemetry("option",{raw_query:A(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(m=>m.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(P(t.activeFormatType))return;let i=ze({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,DATE_RANGE_META_END,DATE_RANGE_META_START,ModeController,OPTIONS_GRID_MOBILE_QUERY,OPTION_ENTER_DELAY_VAR,OPTION_ENTER_FADE_MS,OPTION_ENTER_RISE_MS,OPTION_ENTER_RISE_PX,OPTION_ENTER_STAGGER_MS,PLACEHOLDER_FADE_OUT_MS,PLACEHOLDER_LEAVING_ATTR,PLACEHOLDER_SWAP_GAP_MS,PLACEHOLDER_TYPE_MS,PLACEHOLDER_WORD_PAUSE_MS,PRODUCT_PATH_PREFIX,RANGE_SEPARATOR,SCROLL_ARROW_ATTR,SCROLL_ARROW_BOTTOM_VAR,SCROLL_ARROW_CLASS,SCROLL_ARROW_FADE_MS,SCROLL_ARROW_LABEL,SCROLL_ARROW_SCROLL_IDLE_MS,SCROLL_ARROW_VISIBLE_ATTR,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,attachScrollArrow,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,computeOptionsGridLayout,createStore,cursorIsAtEnd,dateCellMarks,dateSelectionFor,extractPlainText,formatAbsoluteDate,formatDate,formatDateRange,getCursorOffset,getFooterHint,identifiedParamLabel,isCalendarFormat,isOptionsGridMobileViewport,isoDate,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionEnterDelayMs,optionLabel,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,parseLooseDateRange,plainTextLength,planOptionsGrid,previousGraphemeBoundary,productFromMatchedItem,productsFromCustomFields,renderEditableContent,resolveFormatType,resolveIdentifiedDate,sanitizeOptionIconSvg,scrollCaretIntoView,selectedIsoFromText,selectedRangeFor,setCursorOffset,toWireIdentifiedParams,visibleDateRange,withSkippedParams});
1875
+ `;var gt=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(r){return this.report(e,r,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var ht=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...s)=>t(...s);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var bt=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var re=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Wr(n){return(n??we).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Gr(n){return de(n)?`Bearer ${await Te(n).getToken()}`:Ae(n)}async function mi(n){try{let e=Wr(n.apiConfig?.endpoint),t=Ce(n.apiConfig),i=await Gr(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var $r="newParam",fi="suggestionRemoval",qr="selectionAnimation",Vr=650,Ur=0;function Kr(){return`:ac-${++Ur}:`}var gi=170;function hi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var yt=class{constructor(e,t={}){this.inputStore=ft(hi());this._listboxId=Kr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new bt;this.boundary=new gt;this.subscriberCount=0;this.emitter=new ht(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=ai(this.inputStore,i=>In(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new $e(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Je({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Ve(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Ge(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,r)=>{i==="pill"&&r.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new De(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,r)=>this.optionSource.tick(i,r)}),this.keyboardController=new We(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:s}=Ie(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.identifiedParams===r.identifiedParams)return;let o=i.editingIdentified;if(!o||i.identifiedParams.some(l=>l.id===o.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===o.anchor&&l.value===o.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...o,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let r=i.pendingRangeStart;!r||r.key===pe(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let s=o.anchor;if(i.text!==r.text){let l=hn(r.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||fn(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(ui(this.opts.styleRoot??Re(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...hi(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.optionSource.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(Hn(this.domRefs.input),Vt(this.domRefs.dropdown)),this.dropdownRefs&&Vt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:l,removed:c}=Xe(i,r,o);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>r?Math.max(r,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let s=Be(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),I(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let r=W(i);if(!P(r))return!1;let o=U(i.text),s=r==="date-range"||o?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:o?o.start:xe(i),isoEnd:o?o.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!P(t.activeFormatType)||!t.dateView)return;let i=ge(t.dateView,e);this.store.set({dateViewMonth:{...i,key:pe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return $(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.showProducts,r=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==r&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showChipIcons!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.activeFormatType==="date-range"){let r=k(e);if(r){let o=t.dateRangeStart;if(!o){this.store.set({pendingRangeStart:{iso:r,key:pe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(on(o,r));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=si(t,e);if(i){if(this.fireTelemetry("option",{raw_query:A(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(fi),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(fi,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},gi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(qr,()=>this.store.set({inSelectionAnimation:!1}),gi)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");mi({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new re(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showChipIcons(){return e.opts.showChipIcons??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=oi(this.container,t);let i=()=>{this.domRefs&&Kt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Kt(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=ti(this.container,t);let i=()=>{this.dropdownRefs&&Ut(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Ut(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(ue),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule($r,()=>this.store.set({newParamId:null}),Vr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Sn(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=G(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=mn(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);Q(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=A(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let r=t.text.slice(0,i.anchor),o=t.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=o.length===0||o[0]!==" "?`${s} `:s,c=r+l+o,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:H(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg};this.fireTelemetry("option",{raw_query:A(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(f=>f.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(P(t.activeFormatType))return;let i=ze({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,DATE_RANGE_META_END,DATE_RANGE_META_START,ModeController,OPTIONS_GRID_MOBILE_QUERY,OPTION_ENTER_DELAY_VAR,OPTION_ENTER_FADE_MS,OPTION_ENTER_RISE_MS,OPTION_ENTER_RISE_PX,OPTION_ENTER_STAGGER_MS,PLACEHOLDER_FADE_OUT_MS,PLACEHOLDER_LEAVING_ATTR,PLACEHOLDER_SWAP_GAP_MS,PLACEHOLDER_TYPE_MS,PLACEHOLDER_WORD_PAUSE_MS,PRODUCT_PATH_PREFIX,RANGE_SEPARATOR,SCROLL_ARROW_ATTR,SCROLL_ARROW_BOTTOM_VAR,SCROLL_ARROW_CLASS,SCROLL_ARROW_FADE_MS,SCROLL_ARROW_LABEL,SCROLL_ARROW_SCROLL_IDLE_MS,SCROLL_ARROW_VISIBLE_ATTR,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,attachScrollArrow,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,computeOptionsGridLayout,createStore,cursorIsAtEnd,dateCellMarks,dateSelectionFor,extractPlainText,formatAbsoluteDate,formatDate,formatDateRange,getCursorOffset,getFooterHint,identifiedParamLabel,isCalendarFormat,isOptionsGridMobileViewport,isoDate,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionEnterDelayMs,optionLabel,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,parseLooseDateRange,plainTextLength,planOptionsGrid,previousGraphemeBoundary,productFromMatchedItem,productsFromCustomFields,renderEditableContent,resolveFormatType,resolveIdentifiedDate,sanitizeOptionIconSvg,scrollCaretIntoView,selectedIsoFromText,selectedRangeFor,setCursorOffset,toWireIdentifiedParams,visibleDateRange,withSkippedParams});
1836
1876
  //# sourceMappingURL=index.js.map