@magicx-eng/ai-autocomplete-vanilla 0.38.1 → 0.38.2

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