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