@magicx-eng/ai-autocomplete-vanilla 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var qt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var fi=Object.prototype.hasOwnProperty;var hi=(t,e)=>{for(var n in e)qt(t,n,{get:e[n],enumerable:!0})},bi=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of gi(e))!fi.call(t,i)&&i!==n&&qt(t,i,{get:()=>e[i],enumerable:!(r=mi(e,i))||r.enumerable});return t};var Si=t=>bi(qt({},"__esModule",{value:!0}),t);var rs={};hi(rs,{AIAutocomplete:()=>Wt,ATTRIBUTION_URL:()=>ln,DATE_RANGE_META_END:()=>_e,DATE_RANGE_META_START:()=>ke,DEFAULT_OPTION_COUNT_UNIT:()=>mn,ModeController:()=>be,OPTIONS_GRID_MOBILE_QUERY:()=>Te,OPTION_ENTER_DELAY_VAR:()=>It,OPTION_ENTER_FADE_MS:()=>Br,OPTION_ENTER_RISE_MS:()=>Wr,OPTION_ENTER_RISE_PX:()=>qr,OPTION_ENTER_STAGGER_MS:()=>Hr,PLACEHOLDER_FADE_OUT_MS:()=>br,PLACEHOLDER_LEAVING_ATTR:()=>ne,PLACEHOLDER_SWAP_GAP_MS:()=>Sr,PLACEHOLDER_TYPE_MS:()=>fr,PLACEHOLDER_WORD_PAUSE_MS:()=>hr,PRODUCT_PATH_PREFIX:()=>rn,PRODUCT_ROW_PX_PER_LINE:()=>Dr,RANGE_SEPARATOR:()=>Yt,SCHEMA_VERSION:()=>jt,SCROLL_ARROW_ATTR:()=>hn,SCROLL_ARROW_BOTTOM_VAR:()=>xn,SCROLL_ARROW_CLASS:()=>fn,SCROLL_ARROW_FADE_MS:()=>bn,SCROLL_ARROW_LABEL:()=>yn,SCROLL_ARROW_SCROLL_IDLE_MS:()=>Sn,SCROLL_ARROW_VISIBLE_ATTR:()=>re,SKIPPED_PARAM_TEXT:()=>Xt,WEEKDAY_LABELS:()=>xe,addMonths:()=>Oe,attachProductRowWheel:()=>Tt,attachScrollArrow:()=>Rt,buildAttributionUrl:()=>xt,buildDateOptions:()=>Ae,buildQuery:()=>A,buildSubmitResult:()=>U,cellDay:()=>Re,cellIso:()=>N,chipIdFromTap:()=>Ze,computeOptionsGridLayout:()=>an,containScroll:()=>vt,createStore:()=>Nt,cursorIsAtEnd:()=>tt,dateCellMarks:()=>Pt,dateSelectionFor:()=>ge,extractPlainText:()=>we,formatAbsoluteDate:()=>z,formatDate:()=>Vt,formatDateRange:()=>Qt,formatOptionCount:()=>fe,getCursorOffset:()=>k,getFooterHint:()=>yt,identifiedParamLabel:()=>W,isCalendarFormat:()=>v,isOptionsGridMobileViewport:()=>pt,isoDate:()=>D,keepCaretOnChip:()=>et,measureOptionsGrid:()=>ut,monthLabel:()=>Ie,needsOptionsGridMeasurement:()=>dt,optionCountLabel:()=>$r,optionEnterDelayMs:()=>Ot,optionHasImage:()=>Gr,optionImageSrc:()=>B,optionLabel:()=>Lt,optionsEntranceDurationMs:()=>At,optionsGridTemplateColumns:()=>lt,parseDate:()=>ye,parseLooseDate:()=>q,parseLooseDateRange:()=>J,plainTextLength:()=>Je,planOptionsGrid:()=>ct,previousGraphemeBoundary:()=>nt,productFromMatchedItem:()=>on,productInitial:()=>Ct,productRowWheelTarget:()=>cn,productsFromCustomFields:()=>st,renderEditableContent:()=>_t,resolveFormatType:()=>$,resolveIdentifiedDate:()=>De,sameOptionRows:()=>mt,sanitizeOptionIconSvg:()=>he,scrollCaretIntoView:()=>Xe,selectedIsoFromText:()=>Le,selectedRangeFor:()=>ae,setCursorOffset:()=>O,toWireIdentifiedParams:()=>le,visibleDateRange:()=>Et,withSkippedParams:()=>de});module.exports=Si(rs);function $t(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function W(t){let e=$t(t);return e.length>0?e.join(" "):t}function F(t,e){return t.parameter||e}var se=["January","February","March","April","May","June","July","August","September","October","November","December"],xe=["S","M","T","W","T","F","S"],Ln=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Rn="aiaDate",Mn="aiaDay",On=t=>String(t).padStart(2,"0");function D(t){return`${t.getFullYear()}-${On(t.getMonth()+1)}-${On(t.getDate())}`}function Gt(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function xi(t){let e=Gt(t).getTime()-Gt(new Date).getTime();return Math.round(e/864e5)}function Vt(t){let e=xi(t);return e>=0&&e<7?Ln[t.getDay()]:z(t)}function z(t){return t.getFullYear()===new Date().getFullYear()?`${se[t.getMonth()]} ${t.getDate()}`:`${se[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function ye(t){if(!t)return null;let e=Ln.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=Gt(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=se.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 Ie(t){return`${se[t.month]} ${t.year}`}function Ut(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function Dn(t){return{year:t.getFullYear(),month:t.getMonth()}}function Oe(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function An(){return{text:"",is_tappable:!1,kind:null}}function Ae(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(An());for(let i=1;i<=n;i++){let o=new Date(t.year,t.month,i);r.push({text:Vt(o),is_tappable:!0,kind:null,metadata:{[Rn]:D(o),[Mn]:i}})}for(;r.length%xe.length!==0;)r.push(An());return r}function Le(t){let e=ye(t);return e?D(e):null}function N(t){let e=t?.metadata?.[Rn];return typeof e=="string"?e:null}function Re(t){let e=t?.metadata?.[Mn];return typeof e=="number"?e:null}function yi(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function kn(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:se.findIndex(n=>n.toLowerCase().startsWith(e))}function vi(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 _n(t,e,n){let r=new Date(t,e,n);return r.getMonth()===e&&r.getDate()===n?r:null}function q(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=_n(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=kn(o[1]);if(l>=0)return Me(l,Number(o[2]),o[3],n)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(r);if(s){let l=kn(s[2]);if(l>=0)return Me(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?Me(d-1,l,a[3],n):d>12&&l<=12?Me(l-1,d,a[3],n):null}return null}function Me(t,e,n,r){if(n){if(n.length!==4)return null;let o=_n(Number(n),t,e);return o?D(o):null}let i=vi(t,e,r);return i?D(i):null}function De(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:q(t.text,e)}var Yt=" - ",ke="aiaDateRangeStart",_e="aiaDateRangeEnd";function ve(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var Kt=/^\d{4}-\d{2}-\d{2}$/;function Nn(t){if(!Kt.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 Ei=/\s+(?:to|through|thru|until|til|till)\s+/g,Pi=/[-–—]/g;function wi(t){let e=[];for(let n of[Ei,Pi]){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 J(t,e={}){if(!t)return null;let n=new Set,r=null;for(let[i,o]of wi(t.trim())){let s=q(i.trim(),e);if(!s)continue;let a=q(o.trim(),e);!a||a<s||(n.add(`${s}|${a}`),r={start:s,end:a})}return n.size===1?r:null}function Qt(t){let e=Nn(t.start),n=Nn(t.end);return!e||!n?"":t.start===t.end?z(e):`${z(e)}${Yt}${z(n)}`}function Fn(t,e){let n=ve(t,e);return{text:Qt(n),is_tappable:!0,kind:null,metadata:{[ke]:n.start,[_e]:n.end}}}function ae(t,e={}){let n=t?.metadata?.[ke],r=t?.metadata?.[_e];return typeof n=="string"&&typeof r=="string"&&Kt.test(n)&&Kt.test(r)?ve(n,r):J(t?.text,e)}function v(t){return t==="date"||t==="date-range"}var Ti=new Set(["date","dates"]),Ci=new Set(["range","ranges","span","period","window"]),Hn=3;function Ii(t){let e={single:0,range:0};if(!t)return e;for(let n of t)n.is_tappable&&(J(n.text)!==null?e.range+=1:q(n.text)!==null&&(e.single+=1));return e}function $(t){if(!t)return"options";if(t.type?.kind==="date")return"date";if(t.type?.kind==="date_range")return"date-range";let e=t.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let n=Ii(t.options);if(n.single+n.range>=Hn&&n.range>n.single)return"date-range";let r=$t(t.parameter);return r.some(i=>Ti.has(i))?r.some(i=>Ci.has(i))?"date-range":"date":n.single>=Hn?"date":"options"}var Ne=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 Oi="https://api.ai-autocomplete.com",Fe=`${Oi}/api/suggest`,Bn=new WeakMap;function Ee(t){return t?.type==="accessToken"}function Ai(t){if(!(!t||Ee(t)))return t}function He(t){let e=Bn.get(t.getAccessToken);return e||(e=new Ne(t),Bn.set(t.getAccessToken,e)),e}function Be(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function We(t){let e=Ai(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function le(t){return t.map(e=>({parameter:e.parameter,text:e.text}))}var Xt="skipped";function de(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:Xt,kind:null}));return r.length>0?[...t,...r]:t}var Li="0.36.0",jt="1.0",Wn=!1;function Ri(t,e){return{placeholder:t.placeholder,parameter:t.parameter,...e&&{text:t.value??t.text},kind:t.kind}}function Mi(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:de(e.map(m=>Ri(m,n)),l??[]),...s&&s.length>0&&{identified_params:le(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:Li,session_id:r,source:o,schema_version:jt}}}async function qn(t,e,n,r,i){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:r,signal:i})}async function $n(t,e,n){let r=n.apiConfig,i=!n.maskCompletedText,o=Mi(t,e,i,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext),s=Be(r),a=r?.endpoint??Fe,l=JSON.stringify(o);if(Ee(r)){let u=He(r),m=await u.getToken(),g=await qn(a,s,m,l,n.signal);if(g.status===401){let h=await u.getToken(!0);g=await qn(a,s,h,l,n.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let d=We(r);!d&&!Wn&&(Wn=!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 qe=/[\p{L}\p{N}]/u,Di=/['\u2019-]/;function Gn(t,e,n){let r=t[e];if(r===void 0)return!1;if(qe.test(r))return!0;let i=t[e+n];return Di.test(r)&&i!==void 0&&qe.test(i)}function ki(t,e,n){let r=e+n.length;return!(qe.test(n[0])&&Gn(t,e-1,-1)||qe.test(n[n.length-1])&&Gn(t,r,1))}function H(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(ki(t,o,e))return o;i===-1&&(i=o)}o=t.indexOf(e,o+1)}return i}function A(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=g=>H(n,a.text,g,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 g=c.length-a.text.length;for(let h of o)h.start>=m+a.text.length&&(h.start+=g,h.end+=g);o.push({start:m,end:m+c.length}),s=m>=s?m+c.length:s+g}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 Z(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 Vn(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 ee(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 ce(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 Un(t,e){return e?t.map(n=>e[n.parameter]?{...n,options:[]}:n):t}function Kn(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 Yn(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 Qn(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 Xn(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 Ge(t,e){let n=[],r=[],i=0;for(let o of e){let s=H(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 jn(t,e){let{located:n}=Ge(t,e);return n.length>0?n[n.length-1].end:0}function zn(t,e,n){let r=[],i=[],o=0;for(let s of n){let a=H(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 Jn(t,e,n=[]){let r=Ge(t,e).located,i=zn(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 Zn(t,e){let{located:n,missing:r}=Ge(t,e);return{valid:n.map(i=>i.param),invalid:r}}function Ve(t,e,n){let r=Ge(t,e).located,{located:i,missing:o}=zn(t,r,n);return{valid:i.map(s=>s.param),invalid:o}}function _i(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var Ni=100,Fi=300,Hi=2,Ue=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?Qn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=crypto.randomUUID(),d=await $n(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(P=>P.source==="identified").map(P=>({id:crypto.randomUUID(),parameter:P.parameter,text:P.text})),u=Un(d.data.suggestions??[],this.getOptionOverrides()),m=d.data.input??[],g=m[m.length-1],h=this.store.get().text,x,y;if(g?.state==="in_progress"){y=!0;let P=h.toLowerCase().lastIndexOf(g.text.toLowerCase());x=P!==-1?P:o}else y=!1,x=o;let p=u.filter(P=>P.parameter!=="placeholder")[0],b=null;if(p&&!v($(p))){let P=Z(h,x,y),w=ce(p.options,P);w&&(b={id:crypto.randomUUID(),placeholder:"",parameter:F(w,p.parameter),text:w.text,value:w.value,kind:w.kind,suggestionParameter:p.parameter,suggestionValueType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:w.metadata,icon:w.icon,icon_svg:w.icon_svg,image_url:w.image_url},u=u.filter(R=>R!==p),this.callbacks.onAutoMatch?.({active:p,matched:w,rawQuery:e}))}let S=d.data.custom_fields??null,E=this.callbacks.productsForResponse?.(S);this.store.set(P=>{let w=b?[...P.completedParams,b]:P.completedParams,R=Ve(P.text,w,c).valid,T=new Set(s.skippedParams.map(M=>M.id)),I=new Set(P.skippedParams.filter(M=>!T.has(M.id)).map(M=>M.parameter));return{suggestions:I.size>0?u.filter(M=>M.parameter==="placeholder"||!I.has(M.parameter)):u,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:x,filterInProgress:y,identifiedParams:R,customFields:S,...E!==void 0?{products:E}:{},...b?{completedParams:w}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:d.meta?.funnel_telemetry===!0})}catch(s){let a=_i(s);i===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(i===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(Hi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ni),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),Fi)}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=Z(r.text,s,r.filterInProgress),d=r.suggestions.filter(S=>S.parameter!=="placeholder")[0],c=v(r.activeFormatType),m=(d&&!c?ee(d.options,a):[]).filter(S=>S.is_tappable),g=d&&!c?ce(d.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!g&&h||$e(r.text,r.completedParams.length,o))return!1;let{rawQuery:x,completedParams:y}=A(r.text,r.completedParams),f=x.length<r.lastRawQuery.length,p=Math.abs(x.length-r.lastRawQuery.length),b=n&&x!==r.lastRawQuery;return f||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}};function Bi(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&&Bi(e)?e:t.ownerDocument??t}function L(t){return t.ownerDocument??t}function Wi(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function er(t){let e=te(t);return!Wi(e)||typeof e.getSelection=="function"?null:e}function tr(t){let e=er(t);if(!e)return null;let n=L(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 zt(t){let n=te(t).getSelection?.();return n||(L(t).getSelection?.()??null)}function V(t){let e=zt(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 Ke(t){let e=zt(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=L(t).createRange();return i.setStart(r.startContainer,r.startOffset),i.setEnd(r.endContainer,r.endOffset),i}function Pe(t,e,n){let r=zt(t);if(!r)return null;if(er(t))return r.collapse(e,n),r;let i=L(t).createRange();return i.setStart(e,n),i.collapse(!0),r.removeAllRanges(),r.addRange(i),r}function Ye(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 Qe=2,qi="magicx-aia";function rr(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function $i(t){let e=L(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(qi))return null;r=r.parentElement}return null}function Xe(t){let e=Ke(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=$i(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+Qe:r.left<o&&(n.scrollLeft-=o-r.left+Qe)}if(n.scrollHeight>n.clientHeight){let o=i.top+n.clientTop,s=o+n.clientHeight;r.bottom>s?n.scrollTop+=r.bottom-s+Qe:r.top<o&&(n.scrollTop-=o-r.top+Qe)}}var or='[contenteditable="false"]',Zt="strong[data-param-id]",ue;function Gi(){if(ue!==void 0)return ue;let t=globalThis.Intl.Segmenter;if(!t)return ue=null,null;try{ue=new t(void 0,{granularity:"grapheme"})}catch{ue=null}return ue??null}function je(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 ze(t){return L(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return je(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function we(t){let e=ze(t),n="",r=e.nextNode();for(;r;)n+=r.data,r=e.nextNode();return n}function Je(t){let e=ze(t),n=0,r=e.nextNode();for(;r;)n+=r.data.length,r=e.nextNode();return n}function k(t){let e=V(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(je(i,t)&&i!==t)return null;let o=0;for(let s=0;s<r&&s<i.childNodes.length;s++)o+=en(i.childNodes[s],t);return o+Jt(i,t)}return n.nodeType!==Node.TEXT_NODE||je(n,t)?null:Jt(n,t)+r}function en(t,e){if(t.nodeType===Node.TEXT_NODE)return je(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+=en(i,e);return r}function Jt(t,e){let n=ze(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=L(t),r=Math.max(0,Math.min(e,Je(t))),i=ze(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)&&(Vi(t,c,r),Xe(t))}function ir(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 Vi(t,e,n){let r=ir(V(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=k(t);return r!==null&&n===`${r}:${e}`}function ar(t){return te(t).activeElement===t}function Ze(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=V(t);return o&&!o.collapsed?null:i.dataset.paramId??null}function et(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+en(n,t),o=k(t);o!=null&&o>=r&&o<=i||O(t,r)}function tt(t){let e=k(t);return e==null?!1:e>=Je(t)}function nt(t,e){if(e<=0)return 0;let n=Gi();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 U(t,e,n=[],r={}){let{rawQuery:i,completedParams:o}=A(t,e);return{query:t.trim(),raw_query:i,completed_params:de(o,n),identified_params:le(r.identifiedParams??[]),is_ready:r.isReady??!1,...r.customFields?{custom_fields:r.customFields}:{}}}function tn(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")?tt(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function nn(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?k(t):null}var rt=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=tn(e.target,n),u=!!n.editingParam;if(!c&&!u&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(d)break;e.preventDefault();let h=v(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(v(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let h=Math.floor((n.filteredOptions.length-1)/s);if(Math.floor(n.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(n.activeDropdownIndex),g=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!d)break;let m=tn(e.target,n),g=!!n.editingParam;if(!m&&!g)break;e.preventDefault();let h=v(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(),v(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(),v(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}tn(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),v(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=nn(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=nn(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let c=nn(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable?this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,r,o):a&&a(U(n.text,n.completedParams,n.skippedParams,{identifiedParams:n.identifiedParams,isReady:n.isReady,customFields:n.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=n.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(c.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=c.indexOf(n.activeDropdownIndex),m;if(u<0)m=e.shiftKey?c.length-1:0;else{let g=e.shiftKey?-1:1;m=(u+g+c.length)%c.length}this.store.set({activeDropdownIndex:c[m]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingTail;this.ctx.exitEditMode?.(),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=>N(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=Ye(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let i=Ye(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=Ye(i,`${r}-option-${e}`);o?o.click():this.ctx.selectOption(n[e])}};var it=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(v(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||Ui(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 Ui(t){return t instanceof Error&&t.name==="AbortError"}var ot=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}=A(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 rn="/products/",lr="https://relative.invalid";function Ki(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 on(t){let e=Ki(t.item_url)??Yi(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 Yi(t){if(!t.handle)return;let e=`${rn}${encodeURIComponent(t.handle)}`;return t.variant_id?`${e}?variant=${encodeURIComponent(t.variant_id)}`:e}function st(t){return(t?.items.matched??[]).map(on)}var at=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 st(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||Qi(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 Qi(t){return t instanceof Error&&t.name==="AbortError"}var Te="(max-width: 768px)";var Xi="var(--aia-option-row-height, 37px)",ji="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function an(t,e){return e?sn(1,Math.min(t,5)):sn(1,Math.min(t,4))}function sn(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Xi} + ${ji})`}}function dt(t,e){return!e&&t>=5}function ct(t,e,n,r){if(!(!e&&t>=5&&zi(n,r))){let s=an(t,e);return{...s,template:lt(s.cols),scrollHintIndices:!e&&t>s.rows?[s.rows-1]:[]}}let o=6;return{...sn(2,3),template:lt(2),scrollHintIndices:t>o?[o-2,o-1]:[]}}function zi(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 ut(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 lt(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function pt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Te).matches}function mt(t,e){return!t||t.length!==e.length?!1:t.every((n,r)=>n.text===e[r].text)}function dr(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 Ce(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 cr(t){if(!t)return Ut();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function Ji(t){let e=ye(t);return e?Dn(e):Ut()}function ur(t,e){let n=Jn(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)?"":Z(t.text,s,t.filterInProgress),d=i?.options??[],c=t.editingParam!=null&&t.editingAnchor!=null,u,m,g,h;if(c&&t.editingParam&&t.editingAnchor!=null){let C=t.editingParam.id,oe=t.completedParams.some(pi=>pi.id===C),Se=t.caretOffset??t.editingAnchor,In=oe?"":t.text.slice(t.editingAnchor,Se);m=In.trim(),g=t.editingParam.options,h=t.editingParam.suggestionParameter,u=ee(t.editingParam.options,In)}else m=l.trim(),g=d,h=i?.parameter,u=ee(d,l);let x=t.optionSearch,y=x!=null&&h!=null&&x.parameter===h;y&&x.status==="done"&&x.query===m&&(u=g);let f=y&&x.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(C=>C.is_tappable));let b=t.editingIdentified,S=c?t.editingParam&&{parameter:t.editingParam.suggestionParameter,options:t.editingParam.options,type:t.editingParam.suggestionValueType}:i,E=b?b.format:$(S),P=c&&v(E)?ae(t.editingParam):null;P&&(E="date-range");let w=null,R=null;if(v(E)){let C=Ce({...t,actionableSuggestions:r}),oe=t.dateViewMonth;w=oe&&oe.key===C?{year:oe.year,month:oe.month}:b?cr(b.iso):P?cr(P.start):Ji(t.editingParam?.text),u=Ae(w);let Se=t.pendingRangeStart;E==="date-range"&&Se&&Se.key===C&&(R=Se.iso)}let T=C=>p?C.is_tappable:!0,I;if(c){let C=t.editingParam?.options??[];I=t.editingParam!=null&&C.filter(T).length===0}else I=i!=null&&d.filter(T).length===0;let j=dr({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:t.isFocused,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||f,pillTapped:t.pillTapped,activePillHasNoOptions:I,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),M=j&&t.activeDropdownIndex>=0&&!!u[t.activeDropdownIndex]?.is_tappable,_=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,ie=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||f||_,Cn=ie&&t.skeletonOptions!==null,ci=Cn&&t.skeletonOptions?t.skeletonOptions:u,ui=Cn?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:r,filteredOptions:u,dropdownLoading:ie,dropdownOptions:ci,dropdownSuggestion:ui,skeletonExiting:_,activeFormatType:E,dateView:w,dateRangeStart:R,placeholderText:o,optionQuery:m,isSearchingOptions:f,isDropdownOpen:j,isActivePillSelected:M}}function gt(t){return t.mode==="fresh"?Zi(t):eo(t)}function Zi(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=Z(e,d,o),u=ce(a.options,c);if(!u)return null;let m=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(m),h=g>=0?g:Math.max(0,e.length-u.text.length),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:F(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 eo(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=ce(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),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,x={id:crypto.randomUUID(),placeholder:"",parameter:F(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,f=0;for(let b=0;b<n.length;b++){let S=H(e,n[b].text,f);if(S!==-1){if(S>=g){y=b;break}f=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 to=6e4;function no(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function ro(t){return(t??Fe).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function io(t){return Ee(t)?`Bearer ${await He(t).getToken()}`:We(t)}async function pr(t){try{let e=ro(t.apiConfig?.endpoint),n=Be(t.apiConfig),r=await io(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&&no(i)<=to&&{keepalive:!0}})}catch{}}function pe(t,e){let n=t.findIndex(r=>r.text===e);return n>=0?n+1:null}function mr(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(jn(t.text,t.completedParams),i.length),l=Vn(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()),g=m>=0?u.slice(m,m+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",parameter:F(e,n.parameter),text:g,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 ft(t){let e=v(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 ht(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 bt=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=H(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===""?ht(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:A(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:r.options.filter(f=>f.text!==e.text).map(f=>f.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,g={id:crypto.randomUUID(),placeholder:"",parameter:F(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(f=>f.id===r.id),x=n.completedParams.filter(f=>f.id!==r.id),y=h>=0?Math.min(h,x.length):x.length;x.splice(y,0,g),this.deps.store.set({text:u,completedParams:x,newParamId:g.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...ft(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,hr=70,br=120,Sr=50,ne="data-aia-placeholder-leaving",me=new WeakMap;function St(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function oo(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function xr(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function yr(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(xr(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(()=>yr(t,e),33+r)}function gr(t,e){xr(t,e,0),e.timer=setTimeout(()=>yr(t,e),33)}function vr(t,e){let n=me.get(t);if(e===""){n&&(St(n),me.delete(t)),t.removeAttribute(ne),delete t.dataset.placeholder;return}if(n?.target===e)return;if(oo(t)){n&&St(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&&St(n),me.set(t,r),i){t.setAttribute(ne,""),r.timer=setTimeout(()=>{r.timer=null,t.removeAttribute(ne),t.isConnected&&gr(t,r)},170);return}t.removeAttribute(ne),gr(t,r)}function Er(t){let e=me.get(t);e&&(St(e),me.delete(t))}var ln="https://ai-autocomplete.com";function xt(t=ln){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 yt(t,e){return t?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}function vt(t){let e=s=>{s.ctrlKey||Pr(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&&!Pr(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 Pr(t,e,n,r){let i=t instanceof Element?t:null;for(;i;){if(r!==0&&so(i,r)||n!==0&&ao(i,n))return!0;if(i===e)break;i=i.parentElement}return!1}var wr=/^(auto|scroll|overlay)$/;function so(t,e){return t.scrollHeight<=t.clientHeight||!wr.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function ao(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!wr.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 Tr=new WeakMap,Cr=new WeakSet;function K(t,e,n){if(Tr.set(t,n),Cr.has(t))return;Cr.add(t);let r=()=>Tr.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 lo={selectedIso:null,selectedRange:null,rangeStart:null};function ge(t){if(!v(t.activeFormatType))return lo;let e=t.editingIdentified;if(e){let{iso:r,isoEnd:i}=e;return{selectedIso:i?null:r,selectedRange:r&&i?ve(r,i):null,rangeStart:t.dateRangeStart}}let n=ae(t.editingParam);return{selectedIso:n?null:Le(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function Et(t){return t.pendingStart?ve(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function Pt(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 X(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 Or(t,e){if(!e.interactive)return null;let n=e.options[Y(t)];return n?.is_tappable?n:null}var co={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=Or(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")&&Or(t,e)&&e.callbacks.onHighlight(Y(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,Y(t))}};function Lr(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=mo(),t.appendChild(l),Q(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}K(l,co,{options:e,callbacks:s,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=Ie(i));let c=l.querySelector(".magicx-aia-datepicker-grid");c&&uo(c,e,n,r,o)}function uo(t,e,n,r,i){let o=D(new Date),s=Et({pendingStart:i.rangeStart,highlightedIso:N(e[n]),selected:i.selectedRange});X(t,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>po(a),update:(a,l,d)=>{let c=N(l),u=Pt(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 po(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=Re(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 mo(){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(Ar("prev","Previous month","\u2039"),n,Ar("next","Next month","\u203A"));let r=document.createElement("div");r.className="magicx-aia-datepicker-weekdays",r.setAttribute("aria-hidden","true");for(let o of xe){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 Ar(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 go={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},Rr=[125,69];function Mr(t,e){return e?1:t===0?.7:t===1?.4:.2}function wt(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,go,{onSelectPill:r,loading:o}),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Rr.length;l++){let d=Rr[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(Mr(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,m=s&&c===n&&!o,g=["magicx-aia-pill"];i&&g.push("magicx-aia-pill--rounded"),o&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(Mr(c,m)),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 dn(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Dr=32;function cn(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 Tt(t){let e=n=>{let r=cn(t,n);r!==null&&(n.preventDefault(),t.scrollLeft=r)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var kr=Intl.Segmenter,_r=kr?new kr(void 0,{granularity:"grapheme"}):null;function Ct(t){let e=t.trim().normalize("NFC").toUpperCase();if(_r)for(let n of _r.segment(e))return n.segment;return Array.from(e)[0]??"?"}var un=new WeakMap,Nr=new WeakMap,fo="Products";function Fr(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=fo;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),Tt(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=>bo(d),create:d=>So(d,r,i,s),update:(d,c,u)=>{d.id=`${n}-product-${u}`,d.dataset.aiaIndex=String(u),Nr.get(d)?.(s)}}),Q(l);for(let d of l.querySelectorAll("[data-aia-product]")){let c=un.get(d);c&&(un.delete(d),c())}}}function pn(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let r of n)r.tabIndex=e?0:-1}var ho="Sold out";function bo(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 So(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(Nr.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=ho,d.appendChild(u)}return i.appendChild(d),un.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 Hr=80,Br=150,Wr=280,qr=16,It="--aia-option-enter-delay";function Ot(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 At(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 B(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 fe(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var mn={one:"item",other:"items"};function $r(t,e=mn){let n=fe(t);if(n===null)return null;let r=typeof e=="string"?e:t===1?e.one:e.other;return r===""?n:`${n} ${r}`}function Gr(t){return B(t.image_url)!==null}var Vr="http://www.w3.org/2000/svg",xo=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function yo(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 vo=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],Eo=/^[a-zA-Z0-9#.,%\s()-]+$/;function Po(t){let e=[];for(let n of vo){let r=t.getAttribute(n);r===null||!Eo.test(r)||/url\s*\(/i.test(r)||e.push(`${n}: ${r.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function Ur(t){for(let e of Array.from(t.attributes))yo(e.name,e.value)&&t.removeAttribute(e.name);Po(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!xo.has(n.localName)||n.namespaceURI!==Vr?n.remove():Ur(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!==Vr||e.getElementsByTagName("parsererror").length>0?null:(Ur(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function Lt(t){return t.text}var Kr=new WeakMap;function wo(t,e,n){let r=e.length,i=pt(),o=Kr.get(t),s=n&&o&&mt(o.options,e)?o.plan:null,a=!s&&!n&&dt(r,i)?ut(t):null,l=s??ct(r,i,a?.rowWidths??null,a?.gridWidth??null);return n||Kr.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 Yr(t,e){if(e.loading||!e.interactive)return null;let n=e.options[Y(t)];return n?.is_tappable?n:null}var To={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=Yr(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)=>{Yr(t,e)&&e.onHighlight(Y(t))},onLeave:(t,e)=>e.onHighlight(-1,Y(t))};function Qr(t,e,n,r,i,o,s,a="",l="below",d=!0,c=!0,u=!0,m=!0){let g=t.querySelector(".aia-grid");if(e.length===0){g?.remove();return}g||(g=document.createElement("div"),g.className="aia-grid magicx-aia-grid",g.setAttribute("data-scroll",""),g.style.setProperty("--aia-grid-min","250px"),g.style.setProperty("--aia-grid-max","1fr"),g.style.setProperty("--aia-grid-gap","0"),t.appendChild(g)),K(g,To,{options:e,onSelect:r,onHighlight:i,loading:s,interactive:m});let h=g.dataset.aiaGroup!==a;g.dataset.aiaGroup=a,Co(g,e,n,o,s,{showIcons:d,showImages:c,showCounts:u});let x=wo(g,e,s);Io(g,e.length,x,s,l),h&&(g.scrollTop=0)}function Co(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=>B(h.image_url)??"":()=>"",g=c?h=>fe(h.item_count)??"":()=>"";X(t,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${g(h)}\0${s}\0${a}`,create:(h,x)=>{let y=Oo(h,i,o);return i||(y.dataset.aiaEntering=""),y},update:(h,x,y)=>{let f=y===n&&!i;h.id=`${r}-option-${y}`,h.dataset.aiaIndex=String(y),h.setAttribute("aria-selected",String(f)),h.classList.toggle("magicx-aia-option--highlighted",f)}})}function Io(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(It,`${Ot(s,n,e,i)}ms`)}delete o.dataset.aiaEntering}}function Oo(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?B(t.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.setAttribute("aria-hidden","true");let g=document.createElement("img");g.setAttribute("alt",""),g.setAttribute("loading","lazy"),g.setAttribute("decoding","async"),g.setAttribute("referrerpolicy","no-referrer"),g.setAttribute("draggable","false"),g.onerror=()=>{g.hidden=!0},g.src=l,m.appendChild(g),a.appendChild(m),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=Lt(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?fe(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 fn="magicx-aia-scroll-arrow",hn="data-aia-scroll-arrow",re="data-aia-visible",bn=1e3,Sn=160,xn="--aia-scroll-arrow-bottom",yn="Scroll down for more options",Ao="[data-aia-products-label]",Lo=4,Ro=8,Mo=240;function Do(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)/Mo),u=1-(1-c)*(1-c);t.scrollTop=i+e*u,c<1?o.call(n,d):r()};o.call(n,d)}function ko(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 Xr(t=document){let e=t.createElement("button");return e.type="button",e.tabIndex=-1,e.className=fn,e.setAttribute(hn,""),e.setAttribute("aria-label",yn),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(ko(t)),e}function _o(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 Rt({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)},bn)}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(Ao),b;if(p){let S=c(p)+p.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:Ro)}n.style.setProperty(xn,`${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>Lo)},g=()=>{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:At(b,_o(e));s=setTimeout(()=>{s=null,m()},S);return}m()},h=()=>{i||s!==null||(d(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},Sn))};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);Do(e,b,r,h)};n.addEventListener("mousedown",x),n.addEventListener("click",y);let f=null;return r&&typeof r.ResizeObserver=="function"&&(f=new r.ResizeObserver(()=>{u(),m()}),f.observe(e)),g(),{update:g,destroy(){i||(i=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,n.disabled=!0,e.removeEventListener("scroll",h),n.removeEventListener("mousedown",x),n.removeEventListener("click",y),f?.disconnect(),n.removeAttribute(re),n.setAttribute("aria-hidden","true"))}}}var No=[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()),vt(e),e}var Mt=new WeakMap;function Fo(t,e){let n=Mt.get(t);if(n||(n={button:Xr(t.ownerDocument),grid:null,controller:null},t.appendChild(n.button),Mt.set(t,n)),n.grid!==e&&(n.controller?.destroy(),n.controller=null,n.grid=e,e)){n.controller=Rt({dropdown:t,grid:e,button:n.button});return}n.controller?.update()}function vn(t){let e=Mt.get(t);e&&(e.controller?.destroy(),Mt.delete(t))}function kt(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,g=s.length>0,h=a&&g,x=n.length>0,y=e.products.length>0,f=i&&(x||h||o||y);if(f?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"),!f){pn(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&&g&&!e.isInputEmpty,S=h||o&&a||b,E=p.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",""),p.insertBefore(E,p.firstChild));let _=E.querySelector(".magicx-aia-pill-scroll");_||(_=document.createElement("span"),_.className="magicx-aia-pill-scroll",_.setAttribute("data-aia-pill-scroll",""),E.insertBefore(_,E.firstChild)),wt(_,a?s:[],0,u,!0,o&&a,l),Wo(E,b,o||e.skipDisabled,s[0],m)}else E&&E.remove();let P=e.suggestions[0],w=P?`${P.parameter} ${P.text}`:"",R=v(e.formatType),T=R&&!o;Qr(p,R?[]:n,r,d,c,e.listboxId,o,w,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Fo(t,p.querySelector(".aia-grid")),Lr(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 I=p.querySelector(".magicx-aia-skeleton-bars");if(o&&(!x||R)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let _ of No){let ie=document.createElement("span");ie.className="magicx-aia-skeleton-bar",ie.style.width=`${_}px`,I.appendChild(ie)}p.appendChild(I)}}else I&&I.remove();Fr(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),pn(t,!0);let j=p.querySelector(".magicx-aia-footer")??$o(),M=r>=0&&!!n[r]?.is_tappable;qo(j,yt(M,e.isInputEmpty)),j.isConnected||p.appendChild(j),Ho(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Ho(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 Bo={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function Wo(t,e,n,r,i){K(t,Bo,{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 qo(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 $o(){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=xt(),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 jr(t,e){let n=Dt(e.listboxId);return t.appendChild(n),{dropdown:n}}function En(t,e,n){let r=ge(e);kt(t.dropdown,{suggestions:e.editingIdentified?[{parameter:e.editingIdentified.parameter,text:W(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 Go=6,Vo=.3;function zr(t){return t<=0?"0px":`${(-Math.min(Vo,2*Go/t)).toFixed(3)}px`}function _t(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",vr(e,d?o:"");let c=n.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?B(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",g=e.dataset.editingParamId??"";if(c===u&&(r??"")===m&&(i??"")===g)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?k(e):null;e.dataset.segKey=c,e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";let x=L(e),y=x.createDocumentFragment(),f=0;for(let p of n)if(f+=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,E=p.param.id===i,P=["magicx-aia-segment","magicx-aia-segment--completed"];S&&P.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),E&&P.push("magicx-aia-segment--editing"),b.className=P.join(" "),b.style.letterSpacing=zr(p.value.length);let w=l?B(p.param.image_url):null;if(w){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("${w}")`),b.appendChild(T),b.dataset.aiaImage=""}let R=!w&&a&&p.param.icon_svg?he(p.param.icon_svg):null;if(R){let T=x.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=R,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=zr(p.value.length),b.textContent=p.value,y.appendChild(b)}else y.appendChild(x.createTextNode(p.value));e.replaceChildren(y),e.dataset.aiaTextLength=String(f),h!=null?O(e,Math.max(0,Math.min(h,f))):s&&ar(e)&&O(e,f)}var Uo='<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 Jr(){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=Uo,t}function Ko(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function Zr(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 ei(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",Ko()?"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=Jr(),i.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),d.setAttribute("data-aia-submit-slot",""),i.appendChild(d));let c=new AbortController,{signal:u}=c,m=!1,g=0,h=()=>{let f=we(s),b=f.length>0&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;e.handleChange(b)},x=()=>{let f=V(s)?.node??null;if(!f||!s.contains(f))return null;let S=(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return S&&sr(s,S)?null:S};if(i.addEventListener("click",f=>{f.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(g=performance.now(),h(),e.handleCaretAfterInput(k(s)))},{signal:u}),L(s).addEventListener("selectionchange",()=>{let f=V(s);if(!f||!s.contains(f.node))return;let p=f.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()-g<50||e.handleCaretMove(k(s))},{signal:u}),s.addEventListener("click",f=>{let p=Ze(s,f.target);p&&(e.startEditingParam(p),et(s,p))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",f=>{let p=f,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){f.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let S=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(S)&&f.preventDefault()}},{signal:u}),s.addEventListener("paste",f=>{f.preventDefault();let p=(f.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=L(s),S=Ke(s);if(!S||!s.contains(S.startContainer))return;S.deleteContents();let E=b.createTextNode(p);S.insertNode(E),S.setStartAfter(E),Pe(s,S.startContainer,S.startOffset),h()},{signal:u}),s.addEventListener("keydown",f=>e.handleKeyDown(f),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",f=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;f.stopPropagation(),e.onSubmit(U(p.text,p.completedParams,p.skippedParams,{identifiedParams:p.identifiedParams,isReady:p.isReady,customFields:p.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let f=V(s);(!f||!s.contains(f.node))&&Pe(s,s,0)}if(typeof ResizeObserver<"u"){let f=new ResizeObserver(()=>Zr(s,a));f.observe(s),c.signal.addEventListener("abort",()=>f.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:r,submitButton:l,abort:c}}function Pn(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 f=!!e.text||e.completedParams.length>0;s.disabled=!f}let m=r.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==m;if(_t({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 f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?wt(i,e.actionableSuggestions,0,l,!1,f,e.isActivePillSelected):dn(i)}else dn(i);Zr(r,i),g?(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:W(e.editingIdentified.parameter),required:!0,options:[]}:null,x=e.dropdownSuggestion??h??e.actionableSuggestions[0],y=ge(e);kt(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:(f,p)=>{p!==void 0&&c.get().activeDropdownIndex!==p||c.set({activeDropdownIndex:f})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:f=>c.set({isFocused:f})})}function Nt(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 ti(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 wn=new WeakSet,ni=new WeakMap;function ii(t){return t.nodeType===Node.DOCUMENT_NODE}function Yo(t){return ii(t)?t:t.ownerDocument}function Qo(t){let e=ni.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(si),ni.set(t,r),r)}catch{return null}}function ri(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=si,e.appendChild(n)}function oi(t){if(typeof document>"u")return;let e=t??document;if(wn.has(e))return;let n=Yo(e);if(ii(e)){let o=e.head??e.documentElement;if(!o)return;ri(n,o),wn.add(e);return}let r=Qo(n),i=e.adoptedStyleSheets;r&&Array.isArray(i)?i.includes(r)||(e.adoptedStyleSheets=[...i,r]):ri(n,e),wn.add(e)}var si=`.aia-stack {
1
+ "use strict";var qt=Object.defineProperty;var ui=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var mi=Object.prototype.hasOwnProperty;var fi=(t,e)=>{for(var n in e)qt(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&&qt(t,i,{get:()=>e[i],enumerable:!(r=ui(e,i))||r.enumerable});return t};var hi=t=>gi(qt({},"__esModule",{value:!0}),t);var Zo={};fi(Zo,{AIAutocomplete:()=>Wt,ATTRIBUTION_URL:()=>an,DATE_RANGE_META_END:()=>at,DATE_RANGE_META_START:()=>st,DEFAULT_OPTION_COUNT_UNIT:()=>pn,ModeController:()=>he,OPTIONS_GRID_MOBILE_QUERY:()=>Te,OPTION_ENTER_DELAY_VAR:()=>It,OPTION_ENTER_FADE_MS:()=>Fr,OPTION_ENTER_RISE_MS:()=>Hr,OPTION_ENTER_RISE_PX:()=>Br,OPTION_ENTER_STAGGER_MS:()=>Nr,PLACEHOLDER_FADE_OUT_MS:()=>gr,PLACEHOLDER_LEAVING_ATTR:()=>ee,PLACEHOLDER_SWAP_GAP_MS:()=>hr,PLACEHOLDER_TYPE_MS:()=>mr,PLACEHOLDER_WORD_PAUSE_MS:()=>fr,PRODUCT_PATH_PREFIX:()=>Zt,PRODUCT_ROW_PX_PER_LINE:()=>Rr,RANGE_SEPARATOR:()=>nn,SCHEMA_VERSION:()=>Gt,SCROLL_ARROW_ATTR:()=>gn,SCROLL_ARROW_BOTTOM_VAR:()=>Sn,SCROLL_ARROW_CLASS:()=>fn,SCROLL_ARROW_FADE_MS:()=>hn,SCROLL_ARROW_LABEL:()=>xn,SCROLL_ARROW_SCROLL_IDLE_MS:()=>bn,SCROLL_ARROW_VISIBLE_ATTR:()=>te,SKIPPED_PARAM_TEXT:()=>$t,WEEKDAY_LABELS:()=>xe,addMonths:()=>He,attachProductRowWheel:()=>Tt,attachScrollArrow:()=>Rt,buildAttributionUrl:()=>xt,buildDateOptions:()=>Be,buildQuery:()=>A,buildSubmitResult:()=>V,cellDay:()=>qe,cellIso:()=>N,chipIdFromTap:()=>Xe,computeOptionsGridLayout:()=>sn,containScroll:()=>vt,createStore:()=>Nt,cursorIsAtEnd:()=>ze,dateCellMarks:()=>Pt,dateSelectionFor:()=>me,extractPlainText:()=>Ee,formatAbsoluteDate:()=>J,formatDate:()=>Ut,formatDateRange:()=>rn,formatOptionCount:()=>fe,getCursorOffset:()=>k,getFooterHint:()=>yt,identifiedParamLabel:()=>$,isCalendarFormat:()=>E,isOptionsGridMobileViewport:()=>pt,isoDate:()=>D,keepCaretOnChip:()=>je,measureOptionsGrid:()=>ut,monthLabel:()=>Fe,needsOptionsGridMeasurement:()=>dt,optionCountLabel:()=>Wr,optionEnterDelayMs:()=>Ot,optionHasImage:()=>qr,optionImageSrc:()=>B,optionLabel:()=>Lt,optionsEntranceDurationMs:()=>At,optionsGridTemplateColumns:()=>lt,parseDate:()=>ye,parseLooseDate:()=>de,parseLooseDateRange:()=>we,plainTextLength:()=>Qe,planOptionsGrid:()=>ct,previousGraphemeBoundary:()=>Je,productFromMatchedItem:()=>en,productInitial:()=>Ct,productRowWheelTarget:()=>dn,productsFromCustomFields:()=>nt,renderEditableContent:()=>_t,resolveFormatType:()=>W,resolveIdentifiedDate:()=>ot,sameOptionRows:()=>mt,sanitizeOptionIconSvg:()=>ge,scrollCaretIntoView:()=>Ue,selectedIsoFromText:()=>We,selectedRangeFor:()=>ce,setCursorOffset:()=>O,toWireIdentifiedParams:()=>ie,visibleDateRange:()=>Et,withSkippedParams:()=>oe});module.exports=hi(Zo);function E(t){return t==="date"||t==="date-range"}function W(t){return t?.type?.kind==="date"?"date":t?.type?.kind==="date_range"?"date-range":"options"}var Ie=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",Oe=`${bi}/api/suggest`,In=new WeakMap;function Se(t){return t?.type==="accessToken"}function Si(t){if(!(!t||Se(t)))return t}function Ae(t){let e=In.get(t.getAccessToken);return e||(e=new Ie(t),In.set(t.getAccessToken,e)),e}function Le(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function Re(t){let e=Si(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function ie(t){return t.map(e=>({parameter:e.parameter,text:e.text}))}var $t="skipped";function oe(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:$t,kind:null}));return r.length>0?[...t,...r]:t}var xi="0.37.0",Gt="1.0",On=!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 u=e.find(m=>m.parameter==="contact"&&m.metadata?.contact_account_count)?.metadata?.contact_account_count,c=typeof u=="number"?u:void 0;return{data:{raw_query:t,completed_params:oe(e.map(m=>yi(m,n)),l??[]),...s&&s.length>0&&{identified_params:ie(s)},...a&&a.length>0&&{recently_suggested:a},...c!=null&&{contact_account_count:c},...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:Gt}}}async function An(t,e,n,r,i){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:r,signal:i})}async function Ln(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=Le(r),a=r?.endpoint??Oe,l=JSON.stringify(o);if(Se(r)){let c=Ae(r),m=await c.getToken(),f=await An(a,s,m,l,n.signal);if(f.status===401){let h=await c.getToken(!0);f=await An(a,s,h,l,n.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let d=Re(r);!d&&!On&&(On=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(s.Authorization=d);let u=await fetch(a,{method:"POST",headers:s,body:l,signal:n.signal});if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}var Me=/[\p{L}\p{N}]/u,Ei=/['\u2019-]/;function Rn(t,e,n){let r=t[e];if(r===void 0)return!1;if(Me.test(r))return!0;let i=t[e+n];return Ei.test(r)&&i!==void 0&&Me.test(i)}function Pi(t,e,n){let r=e+n.length;return!(Me.test(n[0])&&Rn(t,e-1,-1)||Me.test(n[n.length-1])&&Rn(t,r,1))}function F(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 A(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 u=`{{${a.parameter.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,c=f=>F(n,a.text,f,h=>!o.some(x=>h<x.end&&h+a.text.length>x.start)),m=c(s);if(m===-1&&(m=c(0)),m!==-1){n=n.slice(0,m)+u+n.slice(m+a.text.length);let f=u.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+u.length}),s=m>=s?m+u.length:s+f}i.push({...a,placeholder:u})}return{rawQuery:n,completedParams:i}}function q(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function De(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 Mn(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 se(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 $(t){let e=wi(t);return e.length>0?e.join(" "):t}function H(t,e){return t.parameter||e}function kn(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 _n(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 Nn(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 Fn(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 ke(t,e){let n=[],r=[],i=0;for(let o of e){let s=F(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 Hn(t,e){let{located:n}=ke(t,e);return n.length>0?n[n.length-1].end:0}function Bn(t,e,n){let r=[],i=[],o=0;for(let s of n){let a=F(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 Wn(t,e,n=[]){let r=ke(t,e).located,i=Bn(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,u)=>d.start-u.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 qn(t,e){let{located:n,missing:r}=ke(t,e);return{valid:n.map(i=>i.param),invalid:r}}function _e(t,e,n){let r=ke(t,e).located,{located:i,missing:o}=Bn(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 Ci=100,Ii=300,Oi=2,Ne=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?Nn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=crypto.randomUUID(),d=await Ln(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 u=(d.data.input??[]).filter(v=>v.source==="identified").map(v=>({id:crypto.randomUUID(),parameter:v.parameter,text:v.text,...v.type?{type:v.type}:{}})),c=Dn(d.data.suggestions??[],this.getOptionOverrides()),m=d.data.input??[],f=m[m.length-1],h=this.store.get().text,x,y;if(f?.state==="in_progress"){y=!0;let v=h.toLowerCase().lastIndexOf(f.text.toLowerCase());x=v!==-1?v:o}else y=!1,x=o;let p=c.filter(v=>v.parameter!=="placeholder")[0],b=null;if(p&&!E(W(p))){let v=j(h,x,y),w=se(p.options,v);w&&(b={id:crypto.randomUUID(),placeholder:"",parameter:H(w,p.parameter),text:w.text,value:w.value,kind:w.kind,suggestionParameter:p.parameter,suggestionValueType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:w.metadata,icon:w.icon,icon_svg:w.icon_svg,image_url:w.image_url},c=c.filter(R=>R!==p),this.callbacks.onAutoMatch?.({active:p,matched:w,rawQuery:e}))}let S=d.data.custom_fields??null,P=this.callbacks.productsForResponse?.(S);this.store.set(v=>{let w=b?[...v.completedParams,b]:v.completedParams,R=_e(v.text,w,u).valid,T=new Set(s.skippedParams.map(M=>M.id)),I=new Set(v.skippedParams.filter(M=>!T.has(M.id)).map(M=>M.parameter));return{suggestions:I.size>0?c.filter(M=>M.parameter==="placeholder"||!I.has(M.parameter)):c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:x,filterInProgress:y,identifiedParams:R,customFields:S,...P!==void 0?{products:P}:{},...b?{completedParams:w}:{}}}),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)},Ci),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),Ii)}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=q(r.text,r.filterBase,o),a=j(r.text,s,r.filterInProgress),d=r.suggestions.filter(S=>S.parameter!=="placeholder")[0],u=E(r.activeFormatType),m=(d&&!u?z(d.options,a):[]).filter(S=>S.is_tappable),f=d&&!u?se(d.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!f&&h||De(r.text,r.completedParams.length,o))return!1;let{rawQuery:x,completedParams:y}=A(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 ae=["January","February","March","April","May","June","July","August","September","October","November","December"],xe=["S","M","T","W","T","F","S"],Vn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Un="aiaDate",Kn="aiaDay",$n=t=>String(t).padStart(2,"0");function D(t){return`${t.getFullYear()}-${$n(t.getMonth()+1)}-${$n(t.getDate())}`}function Vt(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function Ai(t){let e=Vt(t).getTime()-Vt(new Date).getTime();return Math.round(e/864e5)}function Ut(t){let e=Ai(t);return e>=0&&e<7?Vn[t.getDay()]:J(t)}function J(t){return t.getFullYear()===new Date().getFullYear()?`${ae[t.getMonth()]} ${t.getDate()}`:`${ae[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function ye(t){if(!t)return null;let e=Vn.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=Vt(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=ae.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 Fe(t){return`${ae[t.month]} ${t.year}`}function Kt(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function Yn(t){return{year:t.getFullYear(),month:t.getMonth()}}function He(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function Gn(){return{text:"",is_tappable:!1,kind:null}}function Be(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(Gn());for(let i=1;i<=n;i++){let o=new Date(t.year,t.month,i);r.push({text:Ut(o),is_tappable:!0,kind:null,metadata:{[Un]:D(o),[Kn]:i}})}for(;r.length%xe.length!==0;)r.push(Gn());return r}function We(t){let e=ye(t);return e?D(e):null}function N(t){let e=t?.metadata?.[Un];return typeof e=="string"?e:null}function qe(t){let e=t?.metadata?.[Kn];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 Z(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&Li(e)?e:t.ownerDocument??t}function L(t){return t.ownerDocument??t}function Ri(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Qn(t){let e=Z(t);return!Ri(e)||typeof e.getSelection=="function"?null:e}function Xn(t){let e=Qn(t);if(!e)return null;let n=L(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function jn(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 Yt(t){let n=Z(t).getSelection?.();return n||(L(t).getSelection?.()??null)}function G(t){let e=Yt(t);if(!e||e.rangeCount===0)return null;let n=Xn(t);if(n){let r=jn(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 $e(t){let e=Yt(t);if(!e||e.rangeCount===0)return null;let n=Xn(t);if(!n)return e.getRangeAt(0);let r=jn(e,n);if(!r)return null;let i=L(t).createRange();return i.setStart(r.startContainer,r.startOffset),i.setEnd(r.endContainer,r.endOffset),i}function ve(t,e,n){let r=Yt(t);if(!r)return null;if(Qn(t))return r.collapse(e,n),r;let i=L(t).createRange();return i.setStart(e,n),i.collapse(!0),r.removeAllRanges(),r.addRange(i),r}function Ge(t,e){let n=t?Z(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ve=2,Mi="magicx-aia";function zn(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function Di(t){let e=L(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&&zn(s.overflowX)||o&&zn(s.overflowY))return r}if(r.classList.contains(Mi))return null;r=r.parentElement}return null}function Ue(t){let e=$e(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=Di(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+Ve:r.left<o&&(n.scrollLeft-=o-r.left+Ve)}if(n.scrollHeight>n.clientHeight){let o=i.top+n.clientTop,s=o+n.clientHeight;r.bottom>s?n.scrollTop+=r.bottom-s+Ve:r.top<o&&(n.scrollTop-=o-r.top+Ve)}}var Zn='[contenteditable="false"]',Xt="strong[data-param-id]",le;function ki(){if(le!==void 0)return le;let t=globalThis.Intl.Segmenter;if(!t)return le=null,null;try{le=new t(void 0,{granularity:"grapheme"})}catch{le=null}return le??null}function Ke(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(Zn))return!0;n=n.parentNode}return!1}function Ye(t){return L(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return Ke(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ee(t){let e=Ye(t),n="",r=e.nextNode();for(;r;)n+=r.data,r=e.nextNode();return n}function Qe(t){let e=Ye(t),n=0,r=e.nextNode();for(;r;)n+=r.data.length,r=e.nextNode();return n}function k(t){let e=G(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(Ke(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+Qt(i,t)}return n.nodeType!==Node.TEXT_NODE||Ke(n,t)?null:Qt(n,t)+r}function jt(t,e){if(t.nodeType===Node.TEXT_NODE)return Ke(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(Zn))return 0;let r=0;for(let i of Array.from(n.childNodes))r+=jt(i,e);return r}function Qt(t,e){let n=Ye(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=L(t),r=Math.max(0,Math.min(e,Qe(t))),i=Ye(t),o=0,s=null,a=0,l=i.nextNode(),d=null;for(;l;){let c=l.data.length;if(r<o+c){s=l,a=r-o;break}if(r===o+c){let m=i.nextNode();m?(s=m,a=0):(s=l,a=c);break}o+=c,d=l,l=i.nextNode()}let u=n.createRange();if(s){let c=s.parentElement?.closest('strong[data-seg="completed"]');c&&c!==t&&t.contains(c)?a===0?u.setStartBefore(c):a===s.data.length?u.setStartAfter(c):u.setStart(s,a):u.setStart(s,a)}else d?u.setStart(d,d.data.length):u.setStart(t,0);u.collapse(!0),ve(t,u.startContainer,u.startOffset)&&(_i(t,u,r),Ue(t))}function Jn(t,e){if(!t||!e.contains(t))return null;let r=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(Xt)??null;return r&&e.contains(r)?r:null}function _i(t,e,n){let r=Jn(G(t)?.node??null,t);if(r&&r!==Jn(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${r.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function er(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let r=k(t);return r!==null&&n===`${r}:${e}`}function tr(t){return Z(t).activeElement===t}function Xe(t,e){if(!e||e.nodeType===void 0)return null;let n=e,i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Xt);if(!i||!t.contains(i))return null;let o=G(t);return o&&!o.collapsed?null:i.dataset.paramId??null}function je(t,e){let n=null;for(let s of t.querySelectorAll(Xt))if(s.dataset.paramId===e){n=s;break}if(!n)return;let r=Qt(n,t),i=r+jt(n,t),o=k(t);o!=null&&o>=r&&o<=i||O(t,r)}function ze(t){let e=k(t);return e==null?!1:e>=Qe(t)}function Je(t,e){if(e<=0)return 0;let n=ki();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}=A(t,e);return{query:t.trim(),raw_query:i,completed_params:oe(o,n),identified_params:ie(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")?ze(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Jt(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?k(t):null}var Ze=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 u=zt(e.target,n),c=!!n.editingParam;if(!u&&!c&&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 u=l.indexOf(n.activeDropdownIndex),c=u>0?u-1:l.length-1;this.store.set({activeDropdownIndex:l[c]});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 c=e.target.closest("[data-aia-input]")??e.target,m=n.editingTail;this.ctx.exitEditMode?.(),O(c,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 u=n.activeDropdownIndex-1;u>=0&&n.filteredOptions[u]?.is_tappable&&this.store.set({activeDropdownIndex:u});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let u=Jt(e.target);u!=null&&this.ctx.startEditingParamAtCaret(u)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,c=n.editingAnchor;this.ctx.exitEditMode?.(),O(u,c);break}if(this.ctx.startEditingParamAtCaret){let u=Jt(e.target);u!=null&&this.ctx.startEditingParamAtCaret(u)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let u=Jt(e.target);if(u==null)break;this.ctx.removeParamAtCaret(u)&&e.preventDefault();break}case"Enter":{e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable?this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,r,o):a&&a(V(n.text,n.completedParams,n.skippedParams,{identifiedParams:n.identifiedParams,isReady:n.isReady,customFields:n.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let u=n.filteredOptions.map((f,h)=>f.is_tappable?h:-1).filter(f=>f!==-1);if(u.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?u[u.length-1]:u[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let c=u.indexOf(n.activeDropdownIndex),m;if(c<0)m=e.shiftKey?u.length-1:0;else{let f=e.shiftKey?-1:1;m=(c+f+u.length)%u.length}this.store.set({activeDropdownIndex:u[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 u=e.target.closest("[data-aia-input]")??e.target,c=n.editingTail;this.ctx.exitEditMode?.(),O(u,c)}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=>N(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=Ge(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let i=Ge(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=Ge(i,`${r}-option-${e}`);o?o.click():this.ctx.selectOption(n[e])}};var et=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 tt=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,u)=>u!==e),s=n.suggestions.filter(d=>d.parameter==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=A(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:i.text,otherPills:o.map(u=>u.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 Zt="/products/",nr="https://relative.invalid";function Fi(t){if(!t)return;let e;try{e=new URL(t,`${nr}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===nr?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function en(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=`${Zt}${encodeURIComponent(t.handle)}`;return t.variant_id?`${e}?variant=${encodeURIComponent(t.variant_id)}`:e}function nt(t){return(t?.items.matched??[]).map(en)}var rt=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 nt(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 rr(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:ae.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 ir(t,e,n){let r=new Date(t,e,n);return r.getMonth()===e&&r.getDate()===n?r:null}function de(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=ir(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=rr(o[1]);if(l>=0)return it(l,Number(o[2]),o[3],n)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(r);if(s){let l=rr(s[2]);if(l>=0)return it(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?it(d-1,l,a[3],n):d>12&&l<=12?it(l-1,d,a[3],n):null}return null}function it(t,e,n,r){if(n){if(n.length!==4)return null;let o=ir(Number(n),t,e);return o?D(o):null}let i=qi(t,e,r);return i?D(i):null}function ot(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:de(t.text,e)}var nn=" - ",st="aiaDateRangeStart",at="aiaDateRangeEnd";function Pe(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var tn=/^\d{4}-\d{2}-\d{2}$/;function or(t){if(!tn.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 we(t,e={}){if(!t)return null;let n=new Set,r=null;for(let[i,o]of Vi(t.trim())){let s=de(i.trim(),e);if(!s)continue;let a=de(o.trim(),e);!a||a<s||(n.add(`${s}|${a}`),r={start:s,end:a})}return n.size===1?r:null}function rn(t){let e=or(t.start),n=or(t.end);return!e||!n?"":t.start===t.end?J(e):`${J(e)}${nn}${J(n)}`}function sr(t,e){let n=Pe(t,e);return{text:rn(n),is_tappable:!0,kind:null,metadata:{[st]:n.start,[at]:n.end}}}function ce(t,e={}){let n=t?.metadata?.[st],r=t?.metadata?.[at];return typeof n=="string"&&typeof r=="string"&&tn.test(n)&&tn.test(r)?Pe(n,r):we(t?.text,e)}var Te="(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 sn(t,e){return e?on(1,Math.min(t,5)):on(1,Math.min(t,4))}function on(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Ui} + ${Ki})`}}function dt(t,e){return!e&&t>=5}function ct(t,e,n,r){if(!(!e&&t>=5&&Yi(n,r))){let s=sn(t,e);return{...s,template:lt(s.cols),scrollHintIndices:!e&&t>s.rows?[s.rows-1]:[]}}let o=6;return{...on(2,3),template:lt(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 ut(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 lt(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function pt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Te).matches}function mt(t,e){return!t||t.length!==e.length?!1:t.every((n,r)=>n.text===e[r].text)}function ar(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 Ce(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 lr(t){if(!t)return Kt();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function Qi(t){let e=ye(t);return e?Yn(e):Kt()}function dr(t,e){let n=Wn(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=q(t.text,Math.min(t.filterBase,t.text.length),o),l=s===0&&De(t.text,t.completedParams.length,o)?"":j(t.text,s,t.filterInProgress),d=i?.options??[],u=t.editingParam!=null&&t.editingAnchor!=null,c,m,f,h;if(u&&t.editingParam&&t.editingAnchor!=null){let C=t.editingParam.id,re=t.completedParams.some(ci=>ci.id===C),be=t.caretOffset??t.editingAnchor,Cn=re?"":t.text.slice(t.editingAnchor,be);m=Cn.trim(),f=t.editingParam.options,h=t.editingParam.suggestionParameter,c=z(t.editingParam.options,Cn)}else m=l.trim(),f=d,h=i?.parameter,c=z(d,l);let x=t.optionSearch,y=x!=null&&h!=null&&x.parameter===h;y&&x.status==="done"&&x.query===m&&(c=f);let g=y&&x.status==="loading",p=e.showNonTappableOptions===!1;p&&(c=c.filter(C=>C.is_tappable));let b=t.editingIdentified,S=u?t.editingParam&&{type:t.editingParam.suggestionValueType}:i,P=b?b.format:W(S),v=u&&P==="date-range"?ce(t.editingParam):null,w=null,R=null;if(E(P)){let C=Ce({...t,actionableSuggestions:r}),re=t.dateViewMonth;w=re&&re.key===C?{year:re.year,month:re.month}:b?lr(b.iso):v?lr(v.start):Qi(t.editingParam?.text),c=Be(w);let be=t.pendingRangeStart;P==="date-range"&&be&&be.key===C&&(R=be.iso)}let T=C=>p?C.is_tappable:!0,I;if(u){let C=t.editingParam?.options??[];I=t.editingParam!=null&&C.filter(T).length===0}else I=i!=null&&d.filter(T).length===0;let X=ar({inEditMode:u||b!=null,filteredOptionsLength:c.length,isFocused:t.isFocused,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||g,pillTapped:t.pillTapped,activePillHasNoOptions:I,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),M=X&&t.activeDropdownIndex>=0&&!!c[t.activeDropdownIndex]?.is_tappable,_=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,ne=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||g||_,Tn=ne&&t.skeletonOptions!==null,li=Tn&&t.skeletonOptions?t.skeletonOptions:c,di=Tn?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:r,filteredOptions:c,dropdownLoading:ne,dropdownOptions:li,dropdownSuggestion:di,skeletonExiting:_,activeFormatType:P,dateView:w,dateRangeStart:R,placeholderText:o,optionQuery:m,isSearchingOptions:g,isDropdownOpen:X,isActivePillSelected:M}}function ft(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=q(e,i,l),u=j(e,d,o),c=se(a.options,u);if(!c)return null;let m=c.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),h=f>=0?f:Math.max(0,e.length-c.text.length),x=h+c.text.length,y=e.slice(h,x),p=x<e.length&&e[x]===" "?x+1:x,b={id:crypto.randomUUID(),placeholder:"",parameter:H(c,a.parameter),text:y,value:c.value,kind:c.kind,suggestionParameter:a.parameter,suggestionValueType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:c.metadata,icon:c.icon,icon_svg:c.icon_svg,image_url:c.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=se(r.options,s);if(!a)return null;let l=a.text.toLowerCase(),d=s.toLowerCase().lastIndexOf(l),u=i+Math.max(0,d),c=u+a.text.length,m=e.slice(u,c),f=c<e.length&&e[c]===" "?c+1:c,h=e.length,x={id:crypto.randomUUID(),placeholder:"",parameter:H(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=F(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??Oe).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function eo(t){return Se(t)?`Bearer ${await Ae(t).getToken()}`:Re(t)}async function cr(t){try{let e=Zi(t.apiConfig?.endpoint),n=Le(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 ue(t,e){let n=t.findIndex(r=>r.text===e);return n>=0?n+1:null}function ur(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(Hn(t.text,t.completedParams),i.length),l=Mn(i.slice(a),e.text);l>0&&(i=i.slice(0,i.length-l));let d=i.length>0&&i[i.length-1]!==" ",u=`${i}${d?" ":""}${e.text} `,c=(o||s)&&u.length>0?u[0].toUpperCase()+u.slice(1):u,m=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=m>=0?c.slice(m,m+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",parameter:H(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:c,filterBase:c.length,completedParams:[...t.completedParams,h],newParamId:h.id,caretOffset:c.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:ue(n.options??[],e.text)},consumedSuggestion:n,remainingActionable:x}}function gt(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 ht(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 bt=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=F(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===""?ht(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:A(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:ue(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,u=a.length===0||a[0]!==" "?`${l} `:l,c=s+u+a,m=c.length,f={id:crypto.randomUUID(),placeholder:"",parameter:H(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:c,completedParams:x,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...gt(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=ft({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 mr=33,fr=70,gr=120,hr=50,ee="data-aia-placeholder-leaving",pe=new WeakMap;function St(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 br(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function Sr(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(br(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(()=>Sr(t,e),33+r)}function pr(t,e){br(t,e,0),e.timer=setTimeout(()=>Sr(t,e),33)}function xr(t,e){let n=pe.get(t);if(e===""){n&&(St(n),pe.delete(t)),t.removeAttribute(ee),delete t.dataset.placeholder;return}if(n?.target===e)return;if(to(t)){n&&St(n),t.removeAttribute(ee),pe.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&&St(n),pe.set(t,r),i){t.setAttribute(ee,""),r.timer=setTimeout(()=>{r.timer=null,t.removeAttribute(ee),t.isConnected&&pr(t,r)},170);return}t.removeAttribute(ee),pr(t,r)}function yr(t){let e=pe.get(t);e&&(St(e),pe.delete(t))}var an="https://ai-autocomplete.com";function xt(t=an){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 yt(t,e){return t?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}function vt(t){let e=s=>{s.ctrlKey||vr(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&&!vr(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 vr(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 Er=/^(auto|scroll|overlay)$/;function no(t,e){return t.scrollHeight<=t.clientHeight||!Er.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(!Er.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 Pr=new WeakMap,wr=new WeakSet;function U(t,e,n){if(Pr.set(t,n),wr.has(t))return;wr.add(t);let r=()=>Pr.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 K(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function Y(t){t.offsetWidth}var io={selectedIso:null,selectedRange:null,rangeStart:null};function me(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?Pe(r,i):null,rangeStart:t.dateRangeStart}}let n=ce(t.editingParam);return{selectedIso:n?null:We(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function Et(t){return t.pendingStart?Pe(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function Pt(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 Tr="data-aia-key";function Q(t,e,n){let r=new Map;for(let s of Array.from(t.children)){let a=s.getAttribute(Tr);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(Tr,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[K(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(K(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,K(t))}};function Or(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),Y(l);for(let c of l.querySelectorAll(".magicx-aia-datepicker-nav"))c.disabled=!1}U(l,oo,{options:e,callbacks:s,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=Fe(i));let u=l.querySelector(".magicx-aia-datepicker-grid");u&&so(u,e,n,r,o)}function so(t,e,n,r,i){let o=D(new Date),s=Et({pendingStart:i.rangeStart,highlightedIso:N(e[n]),selected:i.selectedRange});Q(t,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>ao(a),update:(a,l,d)=>{let u=N(l),c=Pt(u,{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",u!=null&&u<o),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===o),a.classList.toggle("magicx-aia-date-cell--selected",c.selected),a.classList.toggle("magicx-aia-date-cell--in-range",c.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=qe(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(Ir("prev","Previous month","\u2039"),n,Ir("next","Next month","\u203A"));let r=document.createElement("div");r.className="magicx-aia-datepicker-weekdays",r.setAttribute("aria-hidden","true");for(let o of xe){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 Ir(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},Ar=[125,69];function Lr(t,e){return e?1:t===0?.7:t===1?.4:.2}function wt(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)),U(a,co,{onSelectPill:r,loading:o}),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Ar.length;l++){let d=Ar[l],u=document.createElement("span");u.setAttribute("data-aia-pill-skeleton",""),u.className=`magicx-aia-pill magicx-aia-pill--skeleton${i?" magicx-aia-pill--rounded":""}`,u.style.width=`${d}px`,u.style.opacity=String(Lr(l,!1)),a.appendChild(u)}return}o?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();Q(a,e,{keyOf:l=>`${l.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,u)=>{let c=l,m=s&&u===n&&!o,f=["magicx-aia-pill"];i&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),c.className=f.join(" "),c.style.width="",c.style.opacity=String(Lr(u,m)),c.dataset.aiaPillIndex=String(u),o?c.setAttribute("data-aia-loading",""):c.removeAttribute("data-aia-loading")}}),Y(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=o}function ln(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Rr=32;function dn(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 Tt(t){let e=n=>{let r=dn(t,n);r!==null&&(n.preventDefault(),t.scrollLeft=r)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var Mr=Intl.Segmenter,Dr=Mr?new Mr(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 cn=new WeakMap,kr=new WeakMap,uo="Products";function _r(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 u=document.createElement("div");u.className="magicx-aia-products-row",u.setAttribute("data-aia-products-row",""),Tt(u),a.append(d,u),t.appendChild(a)}a.setAttribute("data-aia-products-layout",o);let l=a.querySelector(".magicx-aia-products-row");if(l){Q(l,e,{keyOf:d=>mo(d),create:d=>fo(d,r,i,s),update:(d,u,c)=>{d.id=`${n}-product-${c}`,d.dataset.aiaIndex=String(c),kr.get(d)?.(s)}}),Y(l);for(let d of l.querySelectorAll("[data-aia-product]")){let u=cn.get(d);u&&(cn.delete(d),u())}}}function un(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(kr.set(i,c=>{c!==r&&(r=c,a||l())}),s){let c=document.createElement("img");c.onerror=()=>{a=!1,l()},c.className="magicx-aia-product-image",c.src=s,c.alt="",c.loading="lazy",c.decoding="async",o.appendChild(c)}else l();i.appendChild(o);let d=document.createElement("span");if(d.className="magicx-aia-product-body",t.vendor){let c=document.createElement("span");c.className="magicx-aia-product-vendor",c.textContent=t.vendor,d.appendChild(c)}let u=document.createElement("span");if(u.className="magicx-aia-product-title",u.textContent=t.title,d.appendChild(u),t.price){let c=document.createElement("span");c.className="magicx-aia-product-price",c.textContent=t.price,d.appendChild(c)}if(t.available===!1){i.setAttribute("data-aia-product-sold-out","");let c=document.createElement("span");c.className="magicx-aia-product-badge",c.textContent=po,d.appendChild(c)}return i.appendChild(d),cn.set(i,()=>{t.url&&(i.href=t.url),i.addEventListener("click",c=>{c.metaKey||c.ctrlKey||c.shiftKey||c.altKey||c.button!==0||(c.preventDefault(),e(t))})}),i.addEventListener("keydown",c=>{c.key!=="Enter"&&c.key!==" "||(c.preventDefault(),e(t))}),i.addEventListener("focus",()=>n(!0)),i.addEventListener("blur",c=>{c.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),i}var Nr=80,Fr=150,Hr=280,Br=16,It="--aia-option-enter-delay";function Ot(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 At(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 B(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 fe(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var pn={one:"item",other:"items"};function Wr(t,e=pn){let n=fe(t);if(n===null)return null;let r=typeof e=="string"?e:t===1?e.one:e.other;return r===""?n:`${n} ${r}`}function qr(t){return B(t.image_url)!==null}var $r="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 Gr(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!==$r?n.remove():Gr(n)}else e.remove()}function ge(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!==$r||e.getElementsByTagName("parsererror").length>0?null:(Gr(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function Lt(t){return t.text}var Vr=new WeakMap;function yo(t,e,n){let r=e.length,i=pt(),o=Vr.get(t),s=n&&o&&mt(o.options,e)?o.plan:null,a=!s&&!n&&dt(r,i)?ut(t):null,l=s??ct(r,i,a?.rowWidths??null,a?.gridWidth??null);return n||Vr.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,u)=>{d.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(u))}),l.cols}function Ur(t,e){if(e.loading||!e.interactive)return null;let n=e.options[K(t)];return n?.is_tappable?n:null}var vo={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=Ur(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)=>{Ur(t,e)&&e.onHighlight(K(t))},onLeave:(t,e)=>e.onHighlight(-1,K(t))};function Kr(t,e,n,r,i,o,s,a="",l="below",d=!0,u=!0,c=!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)),U(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:u,showCounts:c});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:u}=o,c=l?h=>h.icon??h.icon_svg??"":()=>"",m=d?h=>B(h.image_url)??"":()=>"",f=u?h=>fe(h.item_count)??"":()=>"";Q(t,e,{keyOf:h=>`${h.text}\0${c(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(It,`${Ot(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?B(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?ge(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 u=document.createElement("span");if(u.className="magicx-aia-option-text",u.textContent=Lt(t),a.appendChild(u),t.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=t.tag,a.appendChild(m)}let c=i?fe(t.item_count):null;if(c!==null){let m=document.createElement("span");m.className="magicx-aia-option-count",m.textContent=c,a.appendChild(m),o.dataset.aiaItemCount=String(t.item_count)}return o.appendChild(a),o}var fn="magicx-aia-scroll-arrow",gn="data-aia-scroll-arrow",te="data-aia-visible",hn=1e3,bn=160,Sn="--aia-scroll-arrow-bottom",xn="Scroll down for more options",To="[data-aia-products-label]",Co=4,Io=8,Oo=240;function Ao(t,e,n,r){let i=t.scrollTop,o=n?.requestAnimationFrame,s=t.ownerDocument?.visibilityState==="hidden";if(!o||s||mn(t)){t.scrollTop=i+e,r();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),d=()=>{let u=Math.min(1,(l()-a)/Oo),c=1-(1-u)*(1-u);t.scrollTop=i+e*c,u<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 Yr(t=document){let e=t.createElement("button");return e.type="button",e.tabIndex=-1,e.className=fn,e.setAttribute(gn,""),e.setAttribute("aria-label",xn),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 mn(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Rt({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(te))return;if(n.setAttribute(te,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),mn(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&n.hasAttribute(te)&&(n.disabled=!1)},hn)}else n.removeAttribute(te),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},u=p=>{let b=0,S=p;for(;S&&S!==t;)b+=S.offsetTop,S=S.offsetParent instanceof HTMLElement?S.offsetParent:null;return b},c=()=>{let p=t.querySelector(To),b;if(p){let S=u(p)+p.offsetHeight/2;b=t.clientHeight-S-n.offsetHeight/2}else{let S=u(e),P=r&&Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0;b=t.clientHeight-(S+e.offsetHeight)+(P>0?0:Io)}n.style.setProperty(Sn,`${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>Co)},f=()=>{if(i)return;c();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=mn(e)?0:At(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()},bn))};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(()=>{c(),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(te),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()),vt(e),e}var Mt=new WeakMap;function Do(t,e){let n=Mt.get(t);if(n||(n={button:Yr(t.ownerDocument),grid:null,controller:null},t.appendChild(n.button),Mt.set(t,n)),n.grid!==e&&(n.controller?.destroy(),n.controller=null,n.grid=e,e)){n.controller=Rt({dropdown:t,grid:e,button:n.button});return}n.controller?.update()}function yn(t){let e=Mt.get(t);e&&(e.controller?.destroy(),Mt.delete(t))}function kt(t,e){let{filteredOptions:n,activeIndex:r,isOpen:i,isLoading:o,pills:s,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:u,onPillClick:c,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){un(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 _=P.querySelector(".magicx-aia-pill-scroll");_||(_=document.createElement("span"),_.className="magicx-aia-pill-scroll",_.setAttribute("data-aia-pill-scroll",""),P.insertBefore(_,P.firstChild)),wt(_,a?s:[],0,c,!0,o&&a,l),No(P,b,o||e.skipDisabled,s[0],m)}else P&&P.remove();let v=e.suggestions[0],w=v?`${v.parameter} ${v.text}`:"",R=E(e.formatType),T=R&&!o;Kr(p,R?[]:n,r,d,u,e.listboxId,o,w,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Do(t,p.querySelector(".aia-grid")),Or(p,T?n:[],r,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:u,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let I=p.querySelector(".magicx-aia-skeleton-bars");if(o&&(!x||R)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let _ of Mo){let ne=document.createElement("span");ne.className="magicx-aia-skeleton-bar",ne.style.width=`${_}px`,I.appendChild(ne)}p.appendChild(I)}}else I&&I.remove();_r(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),un(t,!0);let X=p.querySelector(".magicx-aia-footer")??Ho(),M=r>=0&&!!n[r]?.is_tappable;Fo(X,yt(M,e.isInputEmpty)),X.isConnected||p.appendChild(X),ko(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function ko(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){U(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),Y(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=xt(),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 Qr(t,e){let n=Dt(e.listboxId);return t.appendChild(n),{dropdown:n}}function vn(t,e,n){let r=me(e);kt(t.dropdown,{suggestions:e.editingIdentified?[{parameter:e.editingIdentified.parameter,text:$(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 Xr(t){return t<=0?"0px":`${(-Math.min(Wo,2*Bo/t)).toFixed(3)}px`}function _t(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",xr(e,d?o:"");let u=n.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?B(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),c=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(u===c&&(r??"")===m&&(i??"")===f)return;if(u===c){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?k(e):null;e.dataset.segKey=u,e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";let x=L(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,v=["magicx-aia-segment","magicx-aia-segment--completed"];S&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),P&&v.push("magicx-aia-segment--editing"),b.className=v.join(" "),b.style.letterSpacing=Xr(p.value.length);let w=l?B(p.param.image_url):null;if(w){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("${w}")`),b.appendChild(T),b.dataset.aiaImage=""}let R=!w&&a&&p.param.icon_svg?ge(p.param.icon_svg):null;if(R){let T=x.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=R,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=Xr(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&&tr(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 jr(){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 zr(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 Jr(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=jr(),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 u=new AbortController,{signal:c}=u,m=!1,f=0,h=()=>{let g=Ee(s),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},x=()=>{let g=G(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&&er(s,S)?null:S};if(i.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||s.focus()},{signal:c}),s.addEventListener("input",()=>{m||(f=performance.now(),h(),e.handleCaretAfterInput(k(s)))},{signal:c}),L(s).addEventListener("selectionchange",()=>{let g=G(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(k(s))},{signal:c}),s.addEventListener("click",g=>{let p=Xe(s,g.target);p&&(e.startEditingParam(p),je(s,p))},{signal:c}),s.addEventListener("compositionstart",()=>{m=!0},{signal:c}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:c}),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:c}),s.addEventListener("paste",g=>{g.preventDefault();let p=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=L(s),S=$e(s);if(!S||!s.contains(S.startContainer))return;S.deleteContents();let P=b.createTextNode(p);S.insertNode(P),S.setStartAfter(P),ve(s,S.startContainer,S.startOffset),h()},{signal:c}),s.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:c}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),d&&d.addEventListener("click",g=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(V(p.text,p.completedParams,p.skippedParams,{identifiedParams:p.identifiedParams,isReady:p.isReady,customFields:p.customFields}))&&e.afterSubmit?.()},{signal:c}),e.autoFocus!==!1){s.focus();let g=G(s);(!g||!s.contains(g.node))&&ve(s,s,0)}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>zr(s,a));g.observe(s),u.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:r,submitButton:l,abort:u}}function En(t,e,n){let{input:r,inlinePillContainer:i,dropdown:o,submitButton:s}=t,{pillPlacement:a,setActivePill:l,selectOption:d,store:u}=n;r.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${n.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?r.setAttribute("aria-activedescendant",c):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(_t({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?wt(i,e.actionableSuggestions,0,l,!1,g,e.isActivePillSelected):ln(i)}else ln(i);zr(r,i),f?(r.focus(),O(r,e.caretOffset??e.text.length)):e.isFocused&&Ee(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:$(e.editingIdentified.parameter),required:!0,options:[]}:null,x=e.dropdownSuggestion??h??e.actionableSuggestions[0],y=me(e);kt(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&&u.get().activeDropdownIndex!==p||u.set({activeDropdownIndex:g})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:g=>u.set({isFocused:g})})}function Nt(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[u,c]=d;for(let m of n)m(u,c)}}catch(l){throw r.length=0,l}finally{i=!1}}},subscribe:o=>(n.add(o),()=>{n.delete(o)})}}function Zr(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 Pn=new WeakSet,ei=new WeakMap;function ni(t){return t.nodeType===Node.DOCUMENT_NODE}function Go(t){return ni(t)?t:t.ownerDocument}function Vo(t){let e=ei.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(ii),ei.set(t,r),r)}catch{return null}}function ti(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=ii,e.appendChild(n)}function ri(t){if(typeof document>"u")return;let e=t??document;if(Pn.has(e))return;let n=Go(e);if(ni(e)){let o=e.head??e.documentElement;if(!o)return;ti(n,o),Pn.add(e);return}let r=Vo(n),i=e.adoptedStyleSheets;r&&Array.isArray(i)?i.includes(r)||(e.adoptedStyleSheets=[...i,r]):ti(n,e),Pn.add(e)}var ii=`.aia-stack {
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--aia-stack-space, 0.5rem);
@@ -988,6 +988,19 @@
988
988
  pointer-events: none;
989
989
  }
990
990
 
991
+ /* The hint / branding row is at least --aia-footer-row-height tall, the
992
+ height the footer band under the options grid reserves for it
993
+ (appearance.css). The badge is normally the row's tallest item and holds it
994
+ there; without it \u2014 a consumer hiding the brand link, or a phone, where the
995
+ keyboard hint is hidden too \u2014 the row shrank to the hint's 22px or to
996
+ nothing, the footer's plate stopped short of the band and the rows scrolling
997
+ under it showed below the footer (on a phone, the grid ran past the
998
+ dropdown's bottom edge). The product strip zeroes the band and this floor
999
+ with it (--aia-footer-row-min-height, appearance.css). */
1000
+ .magicx-aia-footer-row {
1001
+ min-height: var(--aia-footer-row-min-height, var(--aia-footer-row-height, 23px));
1002
+ }
1003
+
991
1004
  .magicx-aia-footer-key {
992
1005
  display: inline-flex;
993
1006
  align-items: center;
@@ -2141,6 +2154,10 @@
2141
2154
  /* The fade exists to dissolve rows sliding under the footer. With the strip
2142
2155
  in between it has nothing to dissolve and would just wash over the cards. */
2143
2156
  --aia-footer-fade-lead: 0px;
2157
+ /* Nor does the footer's row need to fill a band that is not reserved: it
2158
+ holds that height only to cover the band (the footer-row rule), and here
2159
+ an empty row would just leave a blank strip under the cards. */
2160
+ --aia-footer-row-min-height: 0px;
2144
2161
  }
2145
2162
 
2146
2163
  /* The reserved band the footer overlaps. Declared here, apart from the grid
@@ -2239,5 +2256,5 @@
2239
2256
  background: var(--aia-surface, #ffffff);
2240
2257
  }
2241
2258
  }
2242
- `;var Ft=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 Ht=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 Bt=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 Xo=50,jo=new Set(["search_started","submit","product_click","impression"]),zo="newParam",ai="suggestionRemoval",Jo="selectionAnimation",Tn="skeletonExit",Zo=650,es=0;function ts(){return`:ac-${++es}:`}var li=170,ns=100;function di(){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 Wt=class{constructor(e,n={}){this.inputStore=Nt(di());this._listboxId=ts();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Bt;this.boundary=new Ft;this.subscriberCount=0;this.emitter=new Ht(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;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=ti(this.inputStore,r=>ur(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 ot(this.store,{onPillSelected:({rawQuery:r,selectedPill:i,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:r,selected_pill:i,other_pills:o})}}),this.reEdit=new bt({store:this.store,scheduleSetCursor:r=>this.scheduleSetCursor(r),fireTelemetry:(r,i)=>this.fireTelemetry(r,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new at(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new it(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 Ue(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)}),this.keyboardController=new rt(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()}),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}=Ve(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===Ce(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=Xn(i.text,r.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}r.text.slice(s).trim().length===0||Yn(r.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(oi(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({...di(),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&&(Er(this.domRefs.input),vn(this.domRefs.dropdown)),this.dropdownRefs&&vn(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}=ht(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=nt(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(c=>c.id===e);if(!r)return!1;let i=$(r);if(!v(i))return!1;let o=J(r.text),s=i==="date-range"||o?"date-range":"date",a=0,l=-1;for(let c of n.segments){if(c.type!=="text"&&c.param.id===e){l=a;break}a+=c.value.length}if(l<0)return!1;let d=l+r.text.length;return this.store.set({editingIdentified:{id:e,parameter:r.parameter,anchor:l,tail:d,text:r.text,iso:o?o.start:De(r),isoEnd:o?o.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}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(!v(n.activeFormatType)||!n.dateView)return;let r=Oe(n.dateView,e);this.store.set({dateViewMonth:{...r,key:Ce(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 U(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=N(e);if(i){let o=n.dateRangeStart;if(!o){this.store.set({pendingRangeStart:{iso:i,key:Ce(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Fn(o,i));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(Tn),this.reEdit.selectOption(e);return}let r=mr(n,e);if(r){if(this.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:r.telemetry.selectedOption,other_options:v(n.activeFormatType)?[]:r.telemetry.otherOptions,key:r.telemetry.key,position:v(n.activeFormatType)?null:r.telemetry.position}),this.timers.clear(Tn),this.store.set({...r.patch,...ft(n)}),this.startSelectionAnimationTimer(),this.timers.clear(ai),r.remainingActionable>0){let i=r.consumedSuggestion;this.timers.schedule(ai,()=>{this.store.get().suggestions.includes(i)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==i)}))},li)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Jo,()=>this.store.set({inSelectionAnimation:!1}),li)}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,Xo).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&&jo.has(e))return;if(!r&&e==="option"){let{key:o,position:s,...a}=n;n=a}let i=this.resolveSource();pr({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=ei(this.container,n);let r=()=>{this.domRefs&&Pn(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),Pn(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=jr(this.container,n);let r=()=>{this.dropdownRefs&&En(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),En(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(Te),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(Tn,()=>this.store.set(r),ns)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule(zo,()=>this.store.set({newParamId:null}),Zo)}))}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}=Zn(e,r.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=G(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),r=Kn(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);ee(e.editingParam.options,r).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:r}=A(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:W(r.parameter),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:A(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(v(n.activeFormatType))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 Ft=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 Ht=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 Bt=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 he=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",oi="suggestionRemoval",Qo="selectionAnimation",wn="skeletonExit",Xo=650,jo=0;function zo(){return`:ac-${++jo}:`}var si=170,Jo=100;function ai(){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 Wt=class{constructor(e,n={}){this.inputStore=Nt(ai());this._listboxId=zo();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Bt;this.boundary=new Ft;this.subscriberCount=0;this.emitter=new Ht(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;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=Zr(this.inputStore,r=>dr(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 tt(this.store,{onPillSelected:({rawQuery:r,selectedPill:i,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:r,selected_pill:i,other_pills:o})}}),this.reEdit=new bt({store:this.store,scheduleSetCursor:r=>this.scheduleSetCursor(r),fireTelemetry:(r,i)=>this.fireTelemetry(r,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new rt(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new et(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 Ne(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:ue(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)}),this.keyboardController=new Ze(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()}),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}=_e(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===Ce(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=Fn(i.text,r.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}r.text.slice(s).trim().length===0||_n(r.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(ri(this.opts.styleRoot??Z(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({...ai(),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&&(yr(this.domRefs.input),yn(this.domRefs.dropdown)),this.dropdownRefs&&yn(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}=ht(r,i,o);return this.store.set(u=>({text:l,filterBase:Math.min(u.filterBase>i?Math.max(i,u.filterBase-d):u.filterBase,l.length),...this.withoutChip(u,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let s=Je(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=W(r);if(!E(i))return!1;let o=i==="date-range"?we(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:ot(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=He(n.dateView,e);this.store.set({dateViewMonth:{...r,key:Ce(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=N(e);if(i){let o=n.dateRangeStart;if(!o){this.store.set({pendingRangeStart:{iso:i,key:Ce(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(sr(o,i));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(wn),this.reEdit.selectOption(e);return}let r=ur(n,e);if(r){if(this.fireTelemetry("option",{raw_query:A(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(wn),this.store.set({...r.patch,...gt(n)}),this.startSelectionAnimationTimer(),this.timers.clear(oi),r.remainingActionable>0){let i=r.consumedSuggestion;this.timers.schedule(oi,()=>{this.store.get().suggestions.includes(i)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==i)}))},si)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Qo,()=>this.store.set({inSelectionAnimation:!1}),si)}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();cr({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 he(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=Jr(this.container,n);let r=()=>{this.domRefs&&En(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),En(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=Qr(this.container,n);let r=()=>{this.dropdownRefs&&vn(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),vn(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(Te),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(wn,()=>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}=qn(e,r.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=q(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),r=kn(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}=A(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,u=d.length,c={id:crypto.randomUUID(),placeholder:"",parameter:r.parameter,text:s,value:e.value,kind:e.kind,suggestionParameter:r.parameter,suggestionPlaceholder:$(r.parameter),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[],key:r.parameter,position:null}),this.store.set({text:d,completedParams:[...n.completedParams,c],identifiedParams:n.identifiedParams.filter(m=>m.id!==r.id),newParamId:c.id,filterBase:u,caretOffset:u,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(u),this.fetchNow()}maybePromoteExactMatch(e){let n=this.store.get();if(E(n.activeFormatType))return;let r=ft({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});
2243
2260
  //# sourceMappingURL=index.js.map