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