@magicx-eng/ai-autocomplete-vanilla 0.27.0 → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Tt=Object.defineProperty;var Mi=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var ki=Object.prototype.hasOwnProperty;var Ni=(n,e)=>{for(var t in e)Tt(n,t,{get:e[t],enumerable:!0})},Fi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _i(e))!ki.call(n,o)&&o!==t&&Tt(n,o,{get:()=>e[o],enumerable:!(i=Mi(e,o))||i.enumerable});return n};var Hi=n=>Fi(Tt({},"__esModule",{value:!0}),n);var cr={};Ni(cr,{AIAutocomplete:()=>Pt,ATTRIBUTION_URL:()=>Gt,DATE_RANGE_META_END:()=>Ce,DATE_RANGE_META_START:()=>Te,DEFAULT_OPTION_COUNT_UNIT:()=>Kt,ModeController:()=>ae,OPTIONS_GRID_MOBILE_QUERY:()=>ge,OPTION_ENTER_DELAY_VAR:()=>ct,OPTION_ENTER_FADE_MS:()=>ri,OPTION_ENTER_RISE_MS:()=>si,OPTION_ENTER_RISE_PX:()=>ai,OPTION_ENTER_STAGGER_MS:()=>oi,PLACEHOLDER_FADE_OUT_MS:()=>Vn,PLACEHOLDER_LEAVING_ATTR:()=>z,PLACEHOLDER_SWAP_GAP_MS:()=>Kn,PLACEHOLDER_TYPE_MS:()=>qn,PLACEHOLDER_WORD_PAUSE_MS:()=>Un,PRODUCT_PATH_PREFIX:()=>Ht,PRODUCT_ROW_PX_PER_LINE:()=>ni,RANGE_SEPARATOR:()=>Dt,SCROLL_ARROW_ATTR:()=>Yt,SCROLL_ARROW_BOTTOM_VAR:()=>zt,SCROLL_ARROW_CLASS:()=>Qt,SCROLL_ARROW_FADE_MS:()=>mi,SCROLL_ARROW_LABEL:()=>Xt,SCROLL_ARROW_SCROLL_IDLE_MS:()=>jt,SCROLL_ARROW_VISIBLE_ATTR:()=>be,SKIPPED_PARAM_TEXT:()=>Mt,WEEKDAY_LABELS:()=>de,addMonths:()=>Se,attachProductRowWheel:()=>dt,attachScrollArrow:()=>ft,buildAttributionUrl:()=>ot,buildDateOptions:()=>xe,buildQuery:()=>O,buildSubmitResult:()=>G,cellDay:()=>we,cellIso:()=>N,computeOptionsGridLayout:()=>$t,createStore:()=>St,cursorIsAtEnd:()=>Ge,dateCellMarks:()=>at,dateSelectionFor:()=>oe,extractPlainText:()=>fe,formatAbsoluteDate:()=>U,formatDate:()=>At,formatDateRange:()=>Lt,formatOptionCount:()=>re,getCursorOffset:()=>_,getFooterHint:()=>rt,identifiedParamLabel:()=>H,isCalendarFormat:()=>w,isOptionsGridMobileViewport:()=>Ze,isoDate:()=>L,measureOptionsGrid:()=>Je,monthLabel:()=>ye,needsOptionsGridMeasurement:()=>ze,optionCountLabel:()=>li,optionEnterDelayMs:()=>ut,optionHasImage:()=>di,optionImageSrc:()=>F,optionLabel:()=>mt,optionsEntranceDurationMs:()=>pt,optionsGridTemplateColumns:()=>je,parseDate:()=>ce,parseLooseDate:()=>B,parseLooseDateRange:()=>V,plainTextLength:()=>$e,planOptionsGrid:()=>Xe,previousGraphemeBoundary:()=>qe,productFromMatchedItem:()=>Bt,productRowWheelTarget:()=>Ut,productsFromCustomFields:()=>Qe,renderEditableContent:()=>yt,resolveFormatType:()=>W,resolveIdentifiedDate:()=>Ee,sanitizeOptionIconSvg:()=>se,scrollCaretIntoView:()=>He,selectedIsoFromText:()=>ve,selectedRangeFor:()=>J,setCursorOffset:()=>I,toWireIdentifiedParams:()=>Z,visibleDateRange:()=>st,withSkippedParams:()=>ee});module.exports=Hi(cr);function Ct(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function H(n){let e=Ct(n);return e.length>0?e.join(" "):n}var X=["January","February","March","April","May","June","July","August","September","October","November","December"],de=["S","M","T","W","T","F","S"],sn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],an="aiaDate",ln="aiaDay",on=n=>String(n).padStart(2,"0");function L(n){return`${n.getFullYear()}-${on(n.getMonth()+1)}-${on(n.getDate())}`}function Ot(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Bi(n){let e=Ot(n).getTime()-Ot(new Date).getTime();return Math.round(e/864e5)}function At(n){let e=Bi(n);return e>=0&&e<7?sn[n.getDay()]:U(n)}function U(n){return n.getFullYear()===new Date().getFullYear()?`${X[n.getMonth()]} ${n.getDate()}`:`${X[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ce(n){if(!n)return null;let e=sn.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Ot(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=X.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let o=Number(t[2]),r=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function ye(n){return`${X[n.month]} ${n.year}`}function It(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function dn(n){return{year:n.getFullYear(),month:n.getMonth()}}function Se(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function rn(){return{text:"",is_tappable:!1,kind:null}}function xe(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(rn());for(let o=1;o<=t;o++){let r=new Date(n.year,n.month,o);i.push({text:At(r),is_tappable:!0,kind:null,metadata:{[an]:L(r),[ln]:o}})}for(;i.length%de.length!==0;)i.push(rn());return i}function ve(n){let e=ce(n);return e?L(e):null}function N(n){let e=n?.metadata?.[an];return typeof e=="string"?e:null}function we(n){let e=n?.metadata?.[ln];return typeof e=="number"?e:null}function Wi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function cn(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:X.findIndex(t=>t.toLowerCase().startsWith(e))}function $i(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let o=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=o)return i;let r=new Date(t.getFullYear()+1,n,e);return r.getMonth()===n&&r.getDate()===e?r:null}function un(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function B(n,e={}){if(!n)return null;let t=e.today??new Date,i=Wi(n.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=un(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?L(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(r){let l=cn(r[1]);if(l>=0)return Pe(l,Number(r[2]),r[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=cn(s[2]);if(l>=0)return Pe(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?Pe(c-1,l,a[3],t):c>12&&l<=12?Pe(l-1,c,a[3],t):null}return null}function Pe(n,e,t,i){if(t){if(t.length!==4)return null;let r=un(Number(t),n,e);return r?L(r):null}let o=$i(n,e,i);return o?L(o):null}function Ee(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:B(n.text,e)}var Dt=" - ",Te="aiaDateRangeStart",Ce="aiaDateRangeEnd";function ue(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Rt=/^\d{4}-\d{2}-\d{2}$/;function pn(n){if(!Rt.test(n))return null;let[e,t,i]=n.split("-").map(Number),o=new Date(e,t-1,i);return o.getMonth()===t-1&&o.getDate()===i?o:null}var Gi=/\s+(?:to|through|thru|until|til|till)\s+/g,qi=/[-–—]/g;function Ui(n){let e=[];for(let t of[Gi,qi]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function V(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[o,r]of Ui(n.trim())){let s=B(o.trim(),e);if(!s)continue;let a=B(r.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function Lt(n){let e=pn(n.start),t=pn(n.end);return!e||!t?"":n.start===n.end?U(e):`${U(e)}${Dt}${U(t)}`}function mn(n,e){let t=ue(n,e);return{text:Lt(t),is_tappable:!0,kind:null,metadata:{[Te]:t.start,[Ce]:t.end}}}function J(n,e={}){let t=n?.metadata?.[Te],i=n?.metadata?.[Ce];return typeof t=="string"&&typeof i=="string"&&Rt.test(t)&&Rt.test(i)?ue(t,i):V(n?.text,e)}function w(n){return n==="date"||n==="date-range"}var Vi=new Set(["date","dates"]),Ki=new Set(["range","ranges","span","period","window"]),fn=3;function Qi(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(V(t.text)!==null?e.range+=1:B(t.text)!==null&&(e.single+=1));return e}function W(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Qi(n.options);if(t.single+t.range>=fn&&t.range>t.single)return"date-range";let i=Ct(n.type);return i.some(o=>Vi.has(o))?i.some(o=>Ki.has(o))?"date-range":"date":t.single>=fn?"date":"options"}var Oe=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 Yi="https://api.ai-autocomplete.com",Ae=`${Yi}/api/suggest`,gn=new WeakMap;function pe(n){return n?.type==="accessToken"}function ji(n){if(!(!n||pe(n)))return n}function Ie(n){let e=gn.get(n.getAccessToken);return e||(e=new Oe(n),gn.set(n.getAccessToken,e)),e}function Re(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function De(n){let e=ji(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function Z(n){return n.map(e=>({type:e.type,value:e.text}))}var Mt="skipped";function ee(n,e){if(e.length===0)return n;let t=new Set(n.map(o=>o.type)),i=e.filter(o=>!t.has(o.type)).map(o=>({placeholder:"",type:o.type,text:Mt,kind:null}));return i.length>0?[...n,...i]:n}var zi="0.27.0",hn=!1;function Xi(){return crypto.randomUUID()}function Ji(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function Zi(n,e,t,i,o,r,s,a,l){let c=e.find(u=>u.type==="contact"&&u.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof c=="number"?c:void 0;return{data:{raw_query:n,completed_params:ee(e.map(u=>Ji(u,t)),a??[]),...r&&r.length>0&&{identified_params:Z(r)},...s&&s.length>0&&{recently_suggested:s},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:Xi(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:zi,session_id:i,source:o}}}async function bn(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function yn(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,r=Zi(n,e,o,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Re(i),a=i?.endpoint??Ae,l=JSON.stringify(r);if(pe(i)){let u=Ie(i),p=await u.getToken(),g=await bn(a,s,p,l,t.signal);if(g.status===401){let b=await u.getToken(!0);g=await bn(a,s,b,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=De(i);!c&&!hn&&(hn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(s.Authorization=c);let d=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function O(n,e){let t=n,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let b=t.indexOf(a.text,g);for(;b!==-1&&r.some(y=>b<y.end&&b+a.text.length>y.start);)b=t.indexOf(a.text,b+1);return b},p=u(s);if(p===-1&&(p=u(0)),p!==-1){t=t.slice(0,p)+d+t.slice(p+a.text.length);let g=d.length-a.text.length;for(let b of r)b.start>=p+a.text.length&&(b.start+=g,b.end+=g);r.push({start:p,end:p+d.length}),s=p>=s?p+d.length:s+g}o.push({...a,placeholder:d})}return{rawQuery:t,completedParams:o}}function $(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Le(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function K(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function Sn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function Q(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function te(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function xn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function vn(n,e){let t=0,i=e;for(let o of n)t+=o.value.length,o.type!=="text"&&(i=Math.max(i,t));return i}function wn(n,e){let t=0;for(let i of n){let o=t+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=o}return!0}function Pn(n,e){let t=[],i=new Set;for(let o of[...n,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),t.push({type:o.type,text:o.text}));return t}function En(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),o=0;for(;o<i&&n[o]===e[o];)o++;if(o>=t)return t;let r=0;for(;r<i-o&&n[n.length-1-r]===e[e.length-1-r];)r++;return n.length-r<=t?t+(e.length-n.length):null}function _t(n,e){let t=[],i=[],o=0;for(let r of e){let s=n.indexOf(r.text,o);if(s===-1){i.push(r);continue}t.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:t,missing:i}}function Tn(n,e,t){let i=[],o=[],r=0;for(let s of t){let a=n.indexOf(s.text,r);for(;a!==-1&&e.some(l=>a<l.end&&a+s.text.length>l.start);)a=n.indexOf(s.text,a+1);if(a===-1){o.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:i,missing:o}}function Cn(n,e,t=[]){let i=_t(n,e).located,o=Tn(n,i,t).located,r=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...o.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),s=[],a=0;for(let c of r)c.start>a&&s.push({type:"text",value:n.slice(a,c.start)}),s.push(c.segment),a=c.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function On(n,e){let{located:t,missing:i}=_t(n,e);return{valid:t.map(o=>o.param),invalid:i}}function Me(n,e,t){let i=_t(n,e).located,{located:o,missing:r}=Tn(n,i,t);return{valid:o.map(s=>s.param),invalid:r}}function eo(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var to=100,no=300,io=2,_e=class{constructor(e,t,i,o,r,s,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?Pn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await yn(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(l.data.input??[]).filter(v=>v.source==="identified").map(v=>({id:crypto.randomUUID(),type:v.type,text:v.text})),d=xn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],p=u[u.length-1],g=this.store.get().text,b,y;if(p?.state==="in_progress"){y=!0;let v=g.toLowerCase().lastIndexOf(p.text.toLowerCase());b=v!==-1?v:r}else y=!1,b=r;let f=d.filter(v=>v.type!=="placeholder")[0],m=null;if(f&&!w(W(f))){let v=K(g,b,y),E=te(f.options,v);E&&(m={id:crypto.randomUUID(),placeholder:"",type:f.type,text:E.text,value:E.value,kind:E.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:E.metadata,icon:E.icon,icon_svg:E.icon_svg,image_url:E.image_url},d=d.filter(R=>R!==f),this.callbacks.onAutoMatch?.({active:f,matched:E,rawQuery:e}))}let h=l.data.custom_fields??null,x=this.callbacks.productsForResponse?.(h);this.store.set(v=>{let E=m?[...v.completedParams,m]:v.completedParams,R=Me(v.text,E,c).valid,M=new Set(s.skippedParams.map(C=>C.id)),T=new Set(v.skippedParams.filter(C=>!M.has(C.id)).map(C=>C.type));return{suggestions:T.size>0?d.filter(C=>C.type==="placeholder"||!T.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:b,filterInProgress:y,identifiedParams:R,customFields:h,...x!==void 0?{products:x}:{},...m?{completedParams:E}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=eo(s);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(io)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},to),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),no)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let r=i.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),s=$(i.text,i.filterBase,r),a=K(i.text,s,i.filterInProgress),c=i.suggestions.filter(x=>x.type!=="placeholder")[0],d=w(i.activeFormatType),p=(c&&!d?Q(c.options,a):[]).filter(x=>x.is_tappable),g=c&&!d?te(c.options,a)!==null:!1,b=a.trim().length>0;if(p.length>0&&!g&&b||Le(i.text,i.completedParams.length,r))return!1;let{rawQuery:y,completedParams:S}=O(i.text,i.completedParams),f=y.length<i.lastRawQuery.length,m=Math.abs(y.length-i.lastRawQuery.length),h=t&&y!==i.lastRawQuery;return f||m>=e||h?(this.doFetch(y,S),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function oo(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function Y(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&oo(e)?e:n.ownerDocument??n}function A(n){return n.ownerDocument??n}function ro(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function An(n){let e=Y(n);return!ro(e)||typeof e.getSelection=="function"?null:e}function In(n){let e=An(n);if(!e)return null;let t=A(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function Rn(n,e){let t=n,i;try{i=t.getComposedRanges({shadowRoots:[e]})}catch{i=t.getComposedRanges(e)}return i.length>0?i[0]:null}function kt(n){let t=Y(n).getSelection?.();return t||(A(n).getSelection?.()??null)}function j(n){let e=kt(n);if(!e||e.rangeCount===0)return null;let t=In(n);if(t){let i=Rn(e,t);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function ke(n){let e=kt(n);if(!e||e.rangeCount===0)return null;let t=In(n);if(!t)return e.getRangeAt(0);let i=Rn(e,t);if(!i)return null;let o=A(n).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function me(n,e,t){let i=kt(n);if(!i)return null;if(An(n))return i.collapse(e,t),i;let o=A(n).createRange();return o.setStart(e,t),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ne(n,e){let t=n?Y(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Fe=2,so="magicx-aia";function Dn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function ao(n){let e=A(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=t.getComputedStyle(i);if(o&&Dn(s.overflowX)||r&&Dn(s.overflowY))return i}if(i.classList.contains(so))return null;i=i.parentElement}return null}function He(n){let e=ke(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=ao(n);if(!t||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let r=o.left+t.clientLeft,s=r+t.clientWidth;i.right>s?t.scrollLeft+=i.right-s+Fe:i.left<r&&(t.scrollLeft-=r-i.left+Fe)}if(t.scrollHeight>t.clientHeight){let r=o.top+t.clientTop,s=r+t.clientHeight;i.bottom>s?t.scrollTop+=i.bottom-s+Fe:i.top<r&&(t.scrollTop-=r-i.top+Fe)}}var _n='[contenteditable="false"]',lo="strong[data-param-id]",ne;function co(){if(ne!==void 0)return ne;let n=globalThis.Intl.Segmenter;if(!n)return ne=null,null;try{ne=new n(void 0,{granularity:"grapheme"})}catch{ne=null}return ne??null}function Be(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(_n))return!0;t=t.parentNode}return!1}function We(n){return A(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Be(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function fe(n){let e=We(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function $e(n){let e=We(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function _(n){let e=j(n);if(!e)return null;let t=e.node,i=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let o=t;if(Be(o,n)&&o!==n)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=kn(o.childNodes[s],n);return r+Ln(o,n)}return t.nodeType!==Node.TEXT_NODE||Be(t,n)?null:Ln(t,n)+i}function kn(n,e){if(n.nodeType===Node.TEXT_NODE)return Be(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(_n))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=kn(o,e);return i}function Ln(n,e){let t=We(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function I(n,e){let t=A(n),i=Math.max(0,Math.min(e,$e(n))),o=We(n),r=0,s=null,a=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(i<r+u){s=l,a=i-r;break}if(i===r+u){let p=o.nextNode();p?(s=p,a=0):(s=l,a=u);break}r+=u,c=l,l=o.nextNode()}let d=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===s.data.length?d.setStartAfter(u):d.setStart(s,a):d.setStart(s,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),me(n,d.startContainer,d.startOffset)&&(uo(n,d,i),He(n))}function Mn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(lo)??null;return i&&e.contains(i)?i:null}function uo(n,e,t){let i=Mn(j(n)?.node??null,n);if(i&&i!==Mn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${i.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function Nn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=_(n);return i!==null&&t===`${i}:${e}`}function Fn(n){return Y(n).activeElement===n}function Ge(n){let e=_(n);return e==null?!1:e>=$e(n)}function qe(n,e){if(e<=0)return 0;let t=co();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:r}of t.segment(i))r<e&&(o=r);return o}function G(n,e,t=[],i={}){let{rawQuery:o,completedParams:r}=O(n,e);return{query:n.trim(),raw_query:o,completed_params:ee(r,t),identified_params:Z(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Nt(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")?Ge(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Ft(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?_(n):null}var Ue=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=o(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=Nt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let b=w(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:b});break}if(l.length===0)return;this.store.set({activeDropdownIndex:b});break}if(e.preventDefault(),l.length===0)return;if(w(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let b=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===b){this.store.set({activeDropdownIndex:-1});break}}let p=l.indexOf(t.activeDropdownIndex),g=p<l.length-1?p+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let p=Nt(e.target,t),g=!!t.editingParam;if(!p&&!g)break;e.preventDefault();let b=w(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:b});break}if(l.length===0)return;this.store.set({activeDropdownIndex:b});break}if(l.length===0)break;if(e.preventDefault(),w(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),I(u,p);break}Nt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=Ft(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),I(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=Ft(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Ft(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,r):a&&a(G(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,b)=>g.is_tappable?b:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),p;if(u<0)p=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;p=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[p]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),I(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=o;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,t){let i=L(new Date),o=e.filteredOptions.findIndex(s=>N(s)===i);if(o>=0)return o;let r=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?r[r.length-1]:r[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.flat()}getEffectiveColumns(e){let t=Ne(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let o=Ne(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let r=getComputedStyle(o).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(o===t)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,o){let r=Ne(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var Ve=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let r=Math.abs(i.query.length-o.query.length),s=i.query.length<o.query.length;if(t>1&&!s&&r<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(w(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=t(e.query,o.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(r)){this.commit(e,r,i);return}this.setSearch(e,"loading"),this.await(e,r,o.signal,i)}async await(e,t,i,o){let r;try{let s=await t;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||po(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,t,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let r={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:t}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:t};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:r}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function po(n){return n instanceof Error&&n.name==="AbortError"}var Ke=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((c,d)=>d!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=O(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:o.text,otherPills:r.map(d=>d.text)})}let a=[...s,o,...r],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 Ht="/products/",Hn="https://relative.invalid";function mo(n){if(!n)return;let e;try{e=new URL(n,`${Hn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Hn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Bt(n){let e=mo(n.item_url)??(n.handle?`${Ht}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function Qe(n){return(n?.items.matched??[]).map(Bt)}var Ye=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return Qe(e)}async run(e,t,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>t.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,t);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],c=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(c)}catch(s){if(t.aborted||fo(s)||(this.logOnce(s),r()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function fo(n){return n instanceof Error&&n.name==="AbortError"}var ge="(max-width: 768px)";var go="var(--aia-option-row-height, 37px)",ho="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function $t(n,e){return e?Wt(1,Math.min(n,5)):Wt(1,Math.min(n,4))}function Wt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${go} + ${ho})`}}function ze(n,e){return!e&&n>=5}function Xe(n,e,t,i){if(!(!e&&n>=5&&bo(t,i))){let s=$t(n,e);return{...s,template:je(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let r=6;return{...Wt(2,3),template:je(2),scrollHintIndices:n>r?[r-2,r-1]:[]}}function bo(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function Je(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let o=getComputedStyle(n),r=n.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function je(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Ze(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(ge).matches}function Bn(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&c}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function he(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function Wn(n){if(!n)return It();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function yo(n){let e=ce(n);return e?dn(e):It()}function $n(n,e){let t=Cn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(P=>P.type!=="placeholder"),o=i[0],r=n.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" "),s=$(n.text,Math.min(n.filterBase,n.text.length),r),l=s===0&&Le(n.text,n.completedParams.length,r)?"":K(n.text,s,n.filterInProgress),c=o?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,p,g,b;if(d&&n.editingParam&&n.editingAnchor!=null){let P=n.editingParam.id,k=n.completedParams.some(Li=>Li.id===P),le=n.caretOffset??n.editingAnchor,nn=k?"":n.text.slice(n.editingAnchor,le);p=nn.trim(),g=n.editingParam.options,b=n.editingParam.suggestionType,u=Q(n.editingParam.options,nn)}else p=l.trim(),g=c,b=o?.type,u=Q(c,l);let y=n.optionSearch,S=y!=null&&b!=null&&y.type===b;S&&y.status==="done"&&y.query===p&&(u=g);let f=S&&y.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(P=>P.is_tappable));let h=n.editingIdentified,x=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:o,v=h?h.format:W(x),E=d&&w(v)?J(n.editingParam):null;E&&(v="date-range");let R=null,M=null;if(w(v)){let P=he({...n,actionableSuggestions:i}),k=n.dateViewMonth;R=k&&k.key===P?{year:k.year,month:k.month}:h?Wn(h.iso):E?Wn(E.start):yo(n.editingParam?.text),u=xe(R);let le=n.pendingRangeStart;v==="date-range"&&le&&le.key===P&&(M=le.iso)}let T=P=>m?P.is_tappable:!0,D;if(d){let P=n.editingParam?.options??[];D=n.editingParam!=null&&P.filter(T).length===0}else D=o!=null&&c.filter(T).length===0;let C=Bn({inEditMode:d||h!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||f,pillTapped:n.pillTapped,activePillHasNoOptions:D,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Et=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:v,dateView:R,dateRangeStart:M,placeholderText:r,optionQuery:p,isSearchingOptions:f,isDropdownOpen:C,isActivePillSelected:Et}}function et(n){return n.mode==="fresh"?So(n):xo(n)}function So(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:r}=n,a=i.filter(x=>x.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),c=$(e,o,l),d=K(e,c,r),u=te(a.options,d);if(!u)return null;let p=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(p),b=g>=0?g:Math.max(0,e.length-u.text.length),y=b+u.text.length,S=e.slice(b,y),m=y<e.length&&e[y]===" "?y+1:y,h={id:crypto.randomUUID(),placeholder:"",type:a.type,text:S,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...t,h],suggestions:i.filter(x=>x!==a),filterBase:m,newParamId:h.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function xo(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:r}=n;if(t.some(h=>h.id===i.id))return null;let s=e.slice(o,r),a=te(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=o+Math.max(0,c),u=d+a.text.length,p=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,b=e.length,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:p,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},S=t.length,f=0;for(let h=0;h<t.length;h++){let x=e.indexOf(t[h].text,f);if(x!==-1){if(x>=g){S=h;break}f=x+t[h].text.length}}let m=[...t];return m.splice(S,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}function tt(n,e,t){let i=n.slice(0,e),o=n.slice(t),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:t-e+(r?1:0)}}var nt=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?tt(t.text,o,r):{text:t.text.slice(0,o)+e+t.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(f=>f.text!==e.text).map(f=>f.text)});let s=t.text.slice(0,o),a=t.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,p=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},b=t.completedParams.findIndex(f=>f.id===i.id),y=t.completedParams.filter(f=>f.id!==i.id),S=b>=0?Math.min(b,y.length):y.length;y.splice(S,0,g),this.deps.store.set({text:u,completedParams:y,newParamId:g.id,filterBase:p,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:p,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(p),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=et({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 qn=33,Un=70,Vn=120,Kn=50,z="data-aia-placeholder-leaving",ie=new WeakMap;function it(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function vo(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Qn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Yn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Qn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Yn(n,e),33+i)}function Gn(n,e){Qn(n,e,0),e.timer=setTimeout(()=>Yn(n,e),33)}function jn(n,e){let t=ie.get(n);if(e===""){t&&(it(t),ie.delete(n)),n.removeAttribute(z),delete n.dataset.placeholder;return}if(t?.target===e)return;if(vo(n)){t&&it(t),n.removeAttribute(z),ie.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=t&&t.shown>0?t:null;if(t&&it(t),ie.set(n,i),o){n.setAttribute(z,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(z),n.isConnected&&Gn(n,i)},170);return}n.removeAttribute(z),Gn(n,i)}function zn(n){let e=ie.get(n);e&&(it(e),ie.delete(n))}var Gt="https://ai-autocomplete.com";function ot(n=Gt){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function rt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var wo={selectedIso:null,selectedRange:null,rangeStart:null};function oe(n){if(!w(n.activeFormatType))return wo;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?ue(i,o):null,rangeStart:n.dateRangeStart}}let t=J(n.editingParam);return{selectedIso:t?null:ve(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function st(n){return n.pendingStart?ue(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function at(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,o=n===t||i!=null&&(n===i.start||n===i.end),r=i!=null&&n>i.start&&n<i.end;return{selected:o,inRange:r}}var Xn="data-aia-key";function q(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Xn);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);o.add(l);let c=i.get(l);c||(c=t.create(a,s),c.setAttribute(Xn,l)),t.update?.(c,a,s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null),r.push(c)}for(let[s,a]of i)o.has(s)||a.remove();return r}function Zn(n,e,t,i,o,r,s){let a=n.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){a?.remove();return}a||(a=To(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=ye(o));let c=a.querySelector("[data-aia-date-prev]"),d=a.querySelector("[data-aia-date-next]");c&&(c.onclick=()=>s.onPreviousMonth()),d&&(d.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&Po(u,e,t,i,r,s)}function Po(n,e,t,i,o,r){let s=L(new Date),a=st({pendingStart:o.rangeStart,highlightedIso:N(e[t]),selected:o.selectedRange});q(n,e,{keyOf:(l,c)=>N(l)??`pad-${c}`,create:l=>Eo(l),update:(l,c,d)=>{let u=N(c),p=at(u,{selectedIso:o.selectedIso,range:a}),g=d===t&&c.is_tappable;l.id=`${i}-option-${d}`,l.dataset.aiaIndex=String(d),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<s),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===s),l.classList.toggle("magicx-aia-date-cell--selected",p.selected),l.classList.toggle("magicx-aia-date-cell--in-range",p.inRange),c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),r.onSelect(c),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let b=Number.parseInt(l.dataset.aiaIndex??"-1",10);b>=0&&r.onHighlight(b)}):(l.onclick=null,l.onmouseenter=null)}})}function Eo(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=we(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function To(){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(Jn("prev","Previous month","\u2039"),t,Jn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of de){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,i.appendChild(s)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),n.append(e,i,o),n}function Jn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",o=>o.preventDefault()),i}var ei=[125,69];function ti(n,e){return e?1:n===0?.7:n===1?.4:.2}function lt(n,e,t,i,o=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<ei.length;l++){let c=ei[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(ti(l,!1)),a.appendChild(d)}return}r?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();q(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.addEventListener("mousedown",d=>d.preventDefault()),c},update:(l,c,d)=>{let u=l,p=s&&d===t&&!r,g=["magicx-aia-pill"];o&&g.push("magicx-aia-pill--rounded"),r&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(ti(d,p)),r?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(d))}})}function qt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ni=32;function Ut(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,i=e.deltaX||0;if(!t||Math.abs(i)>=Math.abs(t))return null;let o=n.scrollWidth-n.clientWidth;if(o<=1)return null;let r=n.scrollLeft,s=t;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=n.clientWidth),Math.max(0,Math.min(o,r+s))}function dt(n){let e=t=>{let i=Ut(n,t);i!==null&&(t.preventDefault(),n.scrollLeft=i)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var Co="Products";function ii(n,e,t,i,o,r="row"){let s=n.querySelector(".magicx-aia-products");if(e.length===0){s?.remove();return}if(!s){s=document.createElement("section"),s.className="magicx-aia-products",s.setAttribute("data-aia-products",""),s.setAttribute("role","group"),s.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=Co;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),dt(c),s.append(l,c),n.appendChild(s)}s.setAttribute("data-aia-products-layout",r);let a=s.querySelector(".magicx-aia-products-row");a&&q(a,e,{keyOf:l=>Oo(l),create:l=>Ao(l,i,o),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}})}function Vt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Oo(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Ao(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),n.url&&(i.href=n.url),i.tabIndex=0;let o=document.createElement("span");if(o.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",o.appendChild(a)}else o.setAttribute("data-aia-product-placeholder","");i.appendChild(o);let r=document.createElement("span");if(r.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,r.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,r.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,r.appendChild(a)}return i.appendChild(r),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var oi=80,ri=150,si=280,ai=16,ct="--aia-option-enter-delay";function ut(n,e,t,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,n)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/o));return Math.max(0,s-1-r)*80}function pt(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 F(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 re(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var Kt={one:"item",other:"items"};function li(n,e=Kt){let t=re(n);if(t===null)return null;let i=typeof e=="string"?e:n===1?e.one:e.other;return i===""?t:`${t} ${i}`}function di(n){return F(n.image_url)!==null}var ci="http://www.w3.org/2000/svg",Io=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function Ro(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 Do=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],Lo=/^[a-zA-Z0-9#.,%\s()-]+$/;function Mo(n){let e=[];for(let t of Do){let i=n.getAttribute(t);i===null||!Lo.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function ui(n){for(let e of Array.from(n.attributes))Ro(e.name,e.value)&&n.removeAttribute(e.name);Mo(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Io.has(t.localName)||t.namespaceURI!==ci?t.remove():ui(t)}else e.remove()}function se(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!==ci||e.getElementsByTagName("parsererror").length>0?null:(ui(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function mt(n){return n.text}function _o(n,e,t){let i=Ze(),o=!t&&ze(e,i)?Je(n):null,r=Xe(e,i,o?.rowWidths??null,o?.gridWidth??null);return n.style.gridTemplateColumns=r.template,n.style.setProperty("--aia-grid-max-height",r.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&r.scrollHintIndices.includes(a))}),r.cols}function pi(n,e,t,i,o,r,s,a="",l="below",c=!0,d=!0,u=!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));let g=p.dataset.aiaGroup!==a;p.dataset.aiaGroup=a,ko(p,e,t,i,o,r,s,{showIcons:c,showImages:d,showCounts:u});let b=_o(p,e.length,s);No(p,e.length,b,s,l),g&&(p.scrollTop=0)}function ko(n,e,t,i,o,r,s,a){let l=s?"1":"0",c=n.dataset.aiaGroup??"",{showIcons:d,showImages:u,showCounts:p}=a,g=d?S=>S.icon??S.icon_svg??"":()=>"",b=u?S=>F(S.image_url)??"":()=>"",y=p?S=>re(S.item_count)??"":()=>"";q(n,e,{keyOf:S=>`${S.text}\0${g(S)}\0${b(S)}\0${y(S)}\0${l}\0${c}`,create:(S,f)=>{let m=Fo(S,s,a);return s||(m.dataset.aiaEntering=""),m},update:(S,f,m)=>{let h=m===t&&!s;S.id=`${r}-option-${m}`,S.dataset.aiaIndex=String(m),S.setAttribute("aria-selected",String(h)),S.classList.toggle("magicx-aia-option--highlighted",h),!s&&f.is_tappable?(S.onclick=()=>{S.classList.add("magicx-aia-option--pressed"),i(f),setTimeout(()=>S.classList.remove("magicx-aia-option--pressed"),170)},S.onmouseenter=()=>{let x=Number.parseInt(S.dataset.aiaIndex??"-1",10);x>=0&&o(x)}):(S.onclick=null,S.onmouseenter=null)}})}function No(n,e,t,i,o){for(let r of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(ct,`${ut(s,t,e,o)}ms`)}delete r.dataset.aiaEntering}}function Fo(n,e,{showIcons:t,showImages:i,showCounts:o}){let r=document.createElement("div");r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),e&&r.setAttribute("data-aia-loading",""),r.tabIndex=e||!n.is_tappable?-1:0;let s=["magicx-aia-option"];n.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),r.className=s.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=i?F(n.image_url):null;if(l){let p=document.createElement("span");p.className="magicx-aia-option-image",p.setAttribute("aria-hidden","true");let g=document.createElement("img");g.setAttribute("alt",""),g.setAttribute("loading","lazy"),g.setAttribute("decoding","async"),g.setAttribute("referrerpolicy","no-referrer"),g.setAttribute("draggable","false"),g.onerror=()=>{g.hidden=!0},g.src=l,p.appendChild(g),a.appendChild(p),r.dataset.aiaImage=""}let c=!l&&t&&n.icon_svg?se(n.icon_svg):null;if(c){let p=document.createElement("span");p.className="magicx-aia-option-icon",p.setAttribute("aria-hidden","true"),p.innerHTML=c,a.appendChild(p),n.icon&&(r.dataset.aiaIcon=n.icon)}let d=document.createElement("span");if(d.className="magicx-aia-option-text",d.textContent=mt(n),a.appendChild(d),n.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=n.tag,a.appendChild(p)}let u=o?re(n.item_count):null;if(u!==null){let p=document.createElement("span");p.className="magicx-aia-option-count",p.textContent=u,a.appendChild(p),r.dataset.aiaItemCount=String(n.item_count)}return r.appendChild(a),r}var Qt="magicx-aia-scroll-arrow",Yt="data-aia-scroll-arrow",be="data-aia-visible",mi=1e3,jt=160,zt="--aia-scroll-arrow-bottom",Xt="Scroll down for more options",Ho="[data-aia-products-label]",Bo=4,Wo=8,$o=240;function Go(n,e,t,i){let o=n.scrollTop,r=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!r||s||gi(n)){n.scrollTop=o+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/$o),u=1-(1-d)*(1-d);n.scrollTop=o+e*u,d<1?r.call(t,c):i()};r.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 i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function fi(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Qt,e.setAttribute(Yt,""),e.setAttribute("aria-label",Xt),e.setAttribute("aria-hidden","true"),e.appendChild(qo(n)),e}function Uo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function gi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function ft({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1,r=null,s=null,a=null,l=f=>{f?(t.setAttribute(be,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(be),t.setAttribute("aria-hidden","true"))},c=f=>{let m=0,h=f;for(;h&&h!==n;)m+=h.offsetTop,h=h.offsetParent instanceof HTMLElement?h.offsetParent:null;return m},d=()=>{let f=n.querySelector(Ho),m;if(f){let h=c(f)+f.offsetHeight/2;m=n.clientHeight-h-t.offsetHeight/2}else{let h=c(e),x=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;m=n.clientHeight-(h+e.offsetHeight)+(x>0?0:Wo)}t.style.setProperty(zt,`${Math.max(0,Math.round(m))}px`)},u=()=>{if(o||s!==null||a!==null)return;let f=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;l(!f&&m>Bo)},p=()=>{if(o)return;d();let f=e.getAttribute("data-aia-group")??"";if(f!==r){r=f,l(!1),s!==null&&clearTimeout(s);let m=e.querySelectorAll("[data-aia-option]").length,h=gi(e)?0:pt(m,Uo(e));s=setTimeout(()=>{s=null,u()},h);return}u()},g=()=>{o||s!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,u()},jt))};e.addEventListener("scroll",g,{passive:!0});let b=f=>f.preventDefault(),y=()=>{let f=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-f);Go(e,m,i,g)};t.addEventListener("mousedown",b),t.addEventListener("click",y);let S=null;return i&&typeof i.ResizeObserver=="function"&&(S=new i.ResizeObserver(()=>{d(),u()}),S.observe(e)),p(),{update:p,destroy(){o||(o=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",b),t.removeEventListener("click",y),S?.disconnect(),t.removeAttribute(be),t.setAttribute("aria-hidden","true"))}}}var Vo=[159,119,164];function ht(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}var gt=new WeakMap;function Ko(n,e){let t=gt.get(n);if(t||(t={button:fi(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),gt.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=ft({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Jt(n){let e=gt.get(n);e&&(e.controller?.destroy(),gt.delete(n))}function bt(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:p}=e,g=s.length>0,b=a&&g,y=t.length>0,S=e.products.length>0,f=o&&(y||b||r||S);if(f?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),r?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!f){Vt(n,!1);return}S?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let h=e.showSkipButton&&g&&!e.isInputEmpty,x=b||r&&a||h,v=m.querySelector(".magicx-aia-pill-bar");if(x){v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar aia-cluster",v.setAttribute("data-nowrap",""),v.setAttribute("data-aia-pillbar",""),m.insertBefore(v,m.firstChild));let P=v.querySelector(".magicx-aia-pill-scroll");P||(P=document.createElement("span"),P.className="magicx-aia-pill-scroll",P.setAttribute("data-aia-pill-scroll",""),v.insertBefore(P,v.firstChild)),lt(P,a?s:[],0,u,!0,r&&a,l),Yo(v,h,r||e.skipDisabled,s[0],p)}else v&&v.remove();let E=e.suggestions[0],R=E?`${E.type} ${E.text}`:"",M=w(e.formatType),T=M&&!r;pi(m,M?[]:t,i,c,d,e.listboxId,r,R,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0),Ko(n,m.querySelector(".aia-grid")),Zn(m,T?t:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let D=m.querySelector(".magicx-aia-skeleton-bars");if(r&&(!y||M)){if(!D){D=document.createElement("div"),D.className="magicx-aia-skeleton-bars",D.setAttribute("data-aia-skeleton-bars","");for(let P of Vo){let k=document.createElement("span");k.className="magicx-aia-skeleton-bar",k.style.width=`${P}px`,D.appendChild(k)}m.appendChild(D)}}else D&&D.remove();ii(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),Vt(n,!0);let C=m.querySelector(".magicx-aia-footer")??zo(),Et=i>=0&&!!t[i]?.is_tappable;jo(C,rt(Et,e.isInputEmpty)),C.isConnected||m.appendChild(C),Qo(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Qo(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function Yo(n,e,t,i,o){let r=n.querySelector(".magicx-aia-skip");if(!e){r?.remove();return}r||(r=document.createElement("button"),r.type="button",r.tabIndex=-1,r.className="magicx-aia-skip",r.setAttribute("data-aia-skip",""),r.textContent="skip",r.addEventListener("mousedown",s=>s.preventDefault()),n.appendChild(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=t,r.onclick=t?null:()=>o()}function jo(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function zo(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=ot(),r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(t,r),n.append(e),n}function hi(n,e){let t=ht(e.listboxId);return n.appendChild(t),{dropdown:t}}function Zt(n,e,t){let i=oe(e);bt(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:H(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:o=>t.store.set({isFocused:o})})}var Xo=6,Jo=.3;function bi(n){return n<=0?"0px":`${(-Math.min(Jo,2*Xo/n)).toFixed(3)}px`}function yt(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",jn(e,c?r:"");let d=t.map(m=>m.type==="completed"?`${m.type}:${m.value}${a?m.param.icon??m.param.icon_svg??"":""}${l?F(m.param.image_url)??"":""}`:`${m.type}:${m.value}`).join("\0"),u=e.dataset.segKey??"",p=e.dataset.newParamId??"",g=e.dataset.editingParamId??"";if(d===u&&(i??"")===p&&(o??"")===g)return;let b=s?_(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let y=A(e),S=y.createDocumentFragment(),f=0;for(let m of t)if(f+=m.value.length,m.type==="completed"){let h=y.createElement("strong");h.dataset.seg="completed",h.dataset.paramId=m.param.id;let x=m.param.id===i,v=m.param.id===o,E=["magicx-aia-segment","magicx-aia-segment--completed"];x&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),v&&E.push("magicx-aia-segment--editing"),h.className=E.join(" "),h.style.letterSpacing=bi(m.value.length);let R=l?F(m.param.image_url):null;if(R){let T=y.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${R}")`),h.appendChild(T),h.dataset.aiaImage=""}let M=!R&&a&&m.param.icon_svg?se(m.param.icon_svg):null;if(M){let T=y.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=M,h.appendChild(T),m.param.icon&&(h.dataset.aiaIcon=m.param.icon)}h.appendChild(y.createTextNode(m.value)),S.appendChild(h)}else if(m.type==="identified"){let h=y.createElement("strong");h.dataset.seg="identified",h.dataset.paramId=m.param.id;let x=["magicx-aia-segment","magicx-aia-segment--completed"];m.param.id===o&&x.push("magicx-aia-segment--editing"),h.className=x.join(" "),h.style.letterSpacing=bi(m.value.length),h.textContent=m.value,S.appendChild(h)}else S.appendChild(y.createTextNode(m.value));e.replaceChildren(S),e.dataset.aiaTextLength=String(f),b!=null?I(e,Math.max(0,Math.min(b,f))):s&&Fn(e)&&I(e,f)}var Zo='<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 yi(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=Zo,n}function er(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Si(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function xi(n,e){let{listboxId:t}=e,i=ht(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",er()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=yi(),o.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",""),o.appendChild(c));let d=new AbortController,{signal:u}=d,p=!1,g=0,b=()=>{let f=fe(s),h=f.length>0&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;e.handleChange(h)},y=()=>{let f=j(s)?.node??null;if(!f||!s.contains(f))return null;let x=(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return x&&Nn(s,x)?null:x};if(o.addEventListener("click",f=>{f.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{p||(g=performance.now(),b(),e.handleCaretAfterInput(_(s)))},{signal:u}),A(s).addEventListener("selectionchange",()=>{let f=j(s);if(!f||!s.contains(f.node))return;let m=f.collapsed?y():null,h=e.store.get(),x=h.editingParam?.id??h.editingIdentified?.id??null;if(m&&m!==x){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(_(s))},{signal:u}),s.addEventListener("compositionstart",()=>{p=!0},{signal:u}),s.addEventListener("compositionend",()=>{p=!1,b()},{signal:u}),s.addEventListener("beforeinput",f=>{let m=f,h=m.inputType;if(h==="insertParagraph"||h==="insertLineBreak"||h==="insertFromDrop"){f.preventDefault();return}if(h.startsWith("insert")||h.startsWith("delete")){let x=h.startsWith("delete")?"":m.data??"";e.replaceEditingRange(x)&&f.preventDefault()}},{signal:u}),s.addEventListener("paste",f=>{f.preventDefault();let m=(f.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let h=A(s),x=ke(s);if(!x||!s.contains(x.startContainer))return;x.deleteContents();let v=h.createTextNode(m);x.insertNode(v),x.setStartAfter(v),me(s,x.startContainer,x.startOffset),b()},{signal:u}),s.addEventListener("keydown",f=>e.handleKeyDown(f),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",f=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;f.stopPropagation(),e.onSubmit(G(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let f=j(s);(!f||!s.contains(f.node))&&me(s,s,0)}if(typeof ResizeObserver<"u"){let f=new ResizeObserver(()=>Si(s,a));f.observe(s),d.signal.addEventListener("abort",()=>f.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function en(n,e,t){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let f=!!e.text||e.completedParams.length>0;s.disabled=!f}let p=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==p;if(yt({input:i,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 f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?lt(o,e.actionableSuggestions,0,l,!1,f,e.isActivePillSelected):qt(o)}else qt(o);Si(i,o),g?(i.focus(),I(i,e.caretOffset??e.text.length)):e.isFocused&&fe(i)!==e.text&&I(i,e.text.length);let b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:H(e.editingIdentified.type),required:!0,options:[]}:null,y=b??e.actionableSuggestions[0],S=oe(e);bt(r,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:b?[b]: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",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:S.selectedIso,selectedDateRange:S.selectedRange,dateRangeStart:S.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:f=>d.set({activeDropdownIndex:f}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:f=>d.set({isFocused:f})})}function vi(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),r=o.length===0&&n.text.length===0,s=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=Sn(o,e.text);a>0&&(o=o.slice(0,o.length-a));let l=o.length>0&&o[o.length-1]!==" ",c=`${o}${l?" ":""}${e.text} `,d=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:p,value:e.value,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},b=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:b}}function St(n){let e=n,t=new Set,i=[],o=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},i.push([e,a]),!o){o=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let p of t)p(d,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(t.add(r),()=>{t.delete(r)})}}function wi(n,e){let t,i,o=r=>(r!==t&&(t=r,i=e(r)),i);return{get:()=>{let r=n.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...o(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let l={...a,...o(a)},c={...s,...o(s)};r(c,l)})}}var tn=new WeakSet,Pi=new WeakMap;function Ti(n){return n.nodeType===Node.DOCUMENT_NODE}function tr(n){return Ti(n)?n:n.ownerDocument}function nr(n){let e=Pi.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(Oi),Pi.set(n,i),i)}catch{return null}}function Ei(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=Oi,e.appendChild(t)}function Ci(n){if(typeof document>"u")return;let e=n??document;if(tn.has(e))return;let t=tr(e);if(Ti(e)){let r=e.head??e.documentElement;if(!r)return;Ei(t,r),tn.add(e);return}let i=nr(t),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):Ei(t,e),tn.add(e)}var Oi=`.aia-stack {
1
+ "use strict";var At=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Gi=Object.getOwnPropertyNames;var qi=Object.prototype.hasOwnProperty;var Ui=(n,e)=>{for(var t in e)At(n,t,{get:e[t],enumerable:!0})},Vi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gi(e))!qi.call(n,o)&&o!==t&&At(n,o,{get:()=>e[o],enumerable:!(i=$i(e,o))||i.enumerable});return n};var Ki=n=>Vi(At({},"__esModule",{value:!0}),n);var wr={};Ui(wr,{AIAutocomplete:()=>Ct,ATTRIBUTION_URL:()=>Vt,DATE_RANGE_META_END:()=>Ie,DATE_RANGE_META_START:()=>Ae,DEFAULT_OPTION_COUNT_UNIT:()=>zt,ModeController:()=>ue,OPTIONS_GRID_MOBILE_QUERY:()=>Se,OPTION_ENTER_DELAY_VAR:()=>mt,OPTION_ENTER_FADE_MS:()=>fi,OPTION_ENTER_RISE_MS:()=>gi,OPTION_ENTER_RISE_PX:()=>hi,OPTION_ENTER_STAGGER_MS:()=>mi,PLACEHOLDER_FADE_OUT_MS:()=>Xn,PLACEHOLDER_LEAVING_ATTR:()=>J,PLACEHOLDER_SWAP_GAP_MS:()=>Jn,PLACEHOLDER_TYPE_MS:()=>jn,PLACEHOLDER_WORD_PAUSE_MS:()=>zn,PRODUCT_PATH_PREFIX:()=>$t,PRODUCT_ROW_PX_PER_LINE:()=>ui,RANGE_SEPARATOR:()=>kt,SCROLL_ARROW_ATTR:()=>Zt,SCROLL_ARROW_BOTTOM_VAR:()=>nn,SCROLL_ARROW_CLASS:()=>Jt,SCROLL_ARROW_FADE_MS:()=>en,SCROLL_ARROW_LABEL:()=>on,SCROLL_ARROW_SCROLL_IDLE_MS:()=>tn,SCROLL_ARROW_VISIBLE_ATTR:()=>Z,SKIPPED_PARAM_TEXT:()=>Nt,WEEKDAY_LABELS:()=>me,addMonths:()=>we,attachProductRowWheel:()=>pt,attachScrollArrow:()=>bt,buildAttributionUrl:()=>at,buildDateOptions:()=>Pe,buildQuery:()=>O,buildSubmitResult:()=>G,cellDay:()=>Te,cellIso:()=>N,computeOptionsGridLayout:()=>Ut,createStore:()=>wt,cursorIsAtEnd:()=>Ve,dateCellMarks:()=>ct,dateSelectionFor:()=>le,extractPlainText:()=>ye,formatAbsoluteDate:()=>K,formatDate:()=>Dt,formatDateRange:()=>_t,formatOptionCount:()=>de,getCursorOffset:()=>k,getFooterHint:()=>lt,identifiedParamLabel:()=>H,isCalendarFormat:()=>w,isOptionsGridMobileViewport:()=>nt,isoDate:()=>L,measureOptionsGrid:()=>tt,monthLabel:()=>ve,needsOptionsGridMeasurement:()=>Ze,optionCountLabel:()=>bi,optionEnterDelayMs:()=>ft,optionHasImage:()=>yi,optionImageSrc:()=>F,optionLabel:()=>ht,optionsEntranceDurationMs:()=>gt,optionsGridTemplateColumns:()=>Je,parseDate:()=>fe,parseLooseDate:()=>B,parseLooseDateRange:()=>Q,plainTextLength:()=>Ue,planOptionsGrid:()=>et,previousGraphemeBoundary:()=>Ke,productFromMatchedItem:()=>Gt,productRowWheelTarget:()=>Qt,productsFromCustomFields:()=>ze,renderEditableContent:()=>vt,resolveFormatType:()=>W,resolveIdentifiedDate:()=>Oe,sanitizeOptionIconSvg:()=>ce,scrollCaretIntoView:()=>$e,selectedIsoFromText:()=>Ee,selectedRangeFor:()=>te,setCursorOffset:()=>I,toWireIdentifiedParams:()=>ne,visibleDateRange:()=>dt,withSkippedParams:()=>ie});module.exports=Ki(wr);function It(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function H(n){let e=It(n);return e.length>0?e.join(" "):n}var ee=["January","February","March","April","May","June","July","August","September","October","November","December"],me=["S","M","T","W","T","F","S"],pn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],mn="aiaDate",fn="aiaDay",cn=n=>String(n).padStart(2,"0");function L(n){return`${n.getFullYear()}-${cn(n.getMonth()+1)}-${cn(n.getDate())}`}function Rt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Qi(n){let e=Rt(n).getTime()-Rt(new Date).getTime();return Math.round(e/864e5)}function Dt(n){let e=Qi(n);return e>=0&&e<7?pn[n.getDay()]:K(n)}function K(n){return n.getFullYear()===new Date().getFullYear()?`${ee[n.getMonth()]} ${n.getDate()}`:`${ee[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function fe(n){if(!n)return null;let e=pn.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Rt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=ee.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let o=Number(t[2]),r=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function ve(n){return`${ee[n.month]} ${n.year}`}function Lt(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function gn(n){return{year:n.getFullYear(),month:n.getMonth()}}function we(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function un(){return{text:"",is_tappable:!1,kind:null}}function Pe(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(un());for(let o=1;o<=t;o++){let r=new Date(n.year,n.month,o);i.push({text:Dt(r),is_tappable:!0,kind:null,metadata:{[mn]:L(r),[fn]:o}})}for(;i.length%me.length!==0;)i.push(un());return i}function Ee(n){let e=fe(n);return e?L(e):null}function N(n){let e=n?.metadata?.[mn];return typeof e=="string"?e:null}function Te(n){let e=n?.metadata?.[fn];return typeof e=="number"?e:null}function Yi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function hn(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:ee.findIndex(t=>t.toLowerCase().startsWith(e))}function ji(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let o=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=o)return i;let r=new Date(t.getFullYear()+1,n,e);return r.getMonth()===n&&r.getDate()===e?r:null}function bn(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function B(n,e={}){if(!n)return null;let t=e.today??new Date,i=Yi(n.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=bn(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?L(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(r){let l=hn(r[1]);if(l>=0)return Ce(l,Number(r[2]),r[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=hn(s[2]);if(l>=0)return Ce(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?Ce(c-1,l,a[3],t):c>12&&l<=12?Ce(l-1,c,a[3],t):null}return null}function Ce(n,e,t,i){if(t){if(t.length!==4)return null;let r=bn(Number(t),n,e);return r?L(r):null}let o=ji(n,e,i);return o?L(o):null}function Oe(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:B(n.text,e)}var kt=" - ",Ae="aiaDateRangeStart",Ie="aiaDateRangeEnd";function ge(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Mt=/^\d{4}-\d{2}-\d{2}$/;function yn(n){if(!Mt.test(n))return null;let[e,t,i]=n.split("-").map(Number),o=new Date(e,t-1,i);return o.getMonth()===t-1&&o.getDate()===i?o:null}var zi=/\s+(?:to|through|thru|until|til|till)\s+/g,Xi=/[-–—]/g;function Ji(n){let e=[];for(let t of[zi,Xi]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function Q(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[o,r]of Ji(n.trim())){let s=B(o.trim(),e);if(!s)continue;let a=B(r.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function _t(n){let e=yn(n.start),t=yn(n.end);return!e||!t?"":n.start===n.end?K(e):`${K(e)}${kt}${K(t)}`}function Sn(n,e){let t=ge(n,e);return{text:_t(t),is_tappable:!0,kind:null,metadata:{[Ae]:t.start,[Ie]:t.end}}}function te(n,e={}){let t=n?.metadata?.[Ae],i=n?.metadata?.[Ie];return typeof t=="string"&&typeof i=="string"&&Mt.test(t)&&Mt.test(i)?ge(t,i):Q(n?.text,e)}function w(n){return n==="date"||n==="date-range"}var Zi=new Set(["date","dates"]),eo=new Set(["range","ranges","span","period","window"]),xn=3;function to(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(Q(t.text)!==null?e.range+=1:B(t.text)!==null&&(e.single+=1));return e}function W(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=to(n.options);if(t.single+t.range>=xn&&t.range>t.single)return"date-range";let i=It(n.type);return i.some(o=>Zi.has(o))?i.some(o=>eo.has(o))?"date-range":"date":t.single>=xn?"date":"options"}var Re=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var no="https://api.ai-autocomplete.com",De=`${no}/api/suggest`,vn=new WeakMap;function he(n){return n?.type==="accessToken"}function io(n){if(!(!n||he(n)))return n}function Le(n){let e=vn.get(n.getAccessToken);return e||(e=new Re(n),vn.set(n.getAccessToken,e)),e}function Me(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function ke(n){let e=io(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ne(n){return n.map(e=>({type:e.type,value:e.text}))}var Nt="skipped";function ie(n,e){if(e.length===0)return n;let t=new Set(n.map(o=>o.type)),i=e.filter(o=>!t.has(o.type)).map(o=>({placeholder:"",type:o.type,text:Nt,kind:null}));return i.length>0?[...n,...i]:n}var oo="0.28.1",wn=!1;function ro(){return crypto.randomUUID()}function so(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function ao(n,e,t,i,o,r,s,a,l){let c=e.find(u=>u.type==="contact"&&u.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof c=="number"?c:void 0;return{data:{raw_query:n,completed_params:ie(e.map(u=>so(u,t)),a??[]),...r&&r.length>0&&{identified_params:ne(r)},...s&&s.length>0&&{recently_suggested:s},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:ro(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:oo,session_id:i,source:o}}}async function Pn(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function En(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,r=ao(n,e,o,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Me(i),a=i?.endpoint??De,l=JSON.stringify(r);if(he(i)){let u=Le(i),m=await u.getToken(),f=await Pn(a,s,m,l,t.signal);if(f.status===401){let h=await u.getToken(!0);f=await Pn(a,s,h,l,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let c=ke(i);!c&&!wn&&(wn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(s.Authorization=c);let d=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function O(n,e){let t=n,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=f=>{let h=t.indexOf(a.text,f);for(;h!==-1&&r.some(S=>h<S.end&&h+a.text.length>S.start);)h=t.indexOf(a.text,h+1);return h},m=u(s);if(m===-1&&(m=u(0)),m!==-1){t=t.slice(0,m)+d+t.slice(m+a.text.length);let f=d.length-a.text.length;for(let h of r)h.start>=m+a.text.length&&(h.start+=f,h.end+=f);r.push({start:m,end:m+d.length}),s=m>=s?m+d.length:s+f}o.push({...a,placeholder:d})}return{rawQuery:t,completedParams:o}}function $(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function _e(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function Y(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function Tn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function j(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function oe(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function Cn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function On(n,e){let t=0,i=e;for(let o of n)t+=o.value.length,o.type!=="text"&&(i=Math.max(i,t));return i}function An(n,e){let t=0;for(let i of n){let o=t+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=o}return!0}function In(n,e){let t=[],i=new Set;for(let o of[...n,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),t.push({type:o.type,text:o.text}));return t}function Rn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),o=0;for(;o<i&&n[o]===e[o];)o++;if(o>=t)return t;let r=0;for(;r<i-o&&n[n.length-1-r]===e[e.length-1-r];)r++;return n.length-r<=t?t+(e.length-n.length):null}function Ft(n,e){let t=[],i=[],o=0;for(let r of e){let s=n.indexOf(r.text,o);if(s===-1){i.push(r);continue}t.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:t,missing:i}}function Dn(n,e,t){let i=[],o=[],r=0;for(let s of t){let a=n.indexOf(s.text,r);for(;a!==-1&&e.some(l=>a<l.end&&a+s.text.length>l.start);)a=n.indexOf(s.text,a+1);if(a===-1){o.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:i,missing:o}}function Ln(n,e,t=[]){let i=Ft(n,e).located,o=Dn(n,i,t).located,r=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...o.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),s=[],a=0;for(let c of r)c.start>a&&s.push({type:"text",value:n.slice(a,c.start)}),s.push(c.segment),a=c.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function Mn(n,e){let{located:t,missing:i}=Ft(n,e);return{valid:t.map(o=>o.param),invalid:i}}function Ne(n,e,t){let i=Ft(n,e).located,{located:o,missing:r}=Dn(n,i,t);return{valid:o.map(s=>s.param),invalid:r}}function lo(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var co=100,uo=300,po=2,Fe=class{constructor(e,t,i,o,r,s,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?In(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await En(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(l.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),d=Cn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],m=u[u.length-1],f=this.store.get().text,h,S;if(m?.state==="in_progress"){S=!0;let x=f.toLowerCase().lastIndexOf(m.text.toLowerCase());h=x!==-1?x:r}else S=!1,h=r;let g=d.filter(x=>x.type!=="placeholder")[0],p=null;if(g&&!w(W(g))){let x=Y(f,h,S),E=oe(g.options,x);E&&(p={id:crypto.randomUUID(),placeholder:"",type:g.type,text:E.text,value:E.value,kind:E.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:E.metadata,icon:E.icon,icon_svg:E.icon_svg,image_url:E.image_url},d=d.filter(R=>R!==g),this.callbacks.onAutoMatch?.({active:g,matched:E,rawQuery:e}))}let b=l.data.custom_fields??null,y=this.callbacks.productsForResponse?.(b);this.store.set(x=>{let E=p?[...x.completedParams,p]:x.completedParams,R=Ne(x.text,E,c).valid,M=new Set(s.skippedParams.map(C=>C.id)),T=new Set(x.skippedParams.filter(C=>!M.has(C.id)).map(C=>C.type));return{suggestions:T.size>0?d.filter(C=>C.type==="placeholder"||!T.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:S,identifiedParams:R,customFields:b,...y!==void 0?{products:y}:{},...p?{completedParams:E}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=lo(s);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(po)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},co),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),uo)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let r=i.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=$(i.text,i.filterBase,r),a=Y(i.text,s,i.filterInProgress),c=i.suggestions.filter(y=>y.type!=="placeholder")[0],d=w(i.activeFormatType),m=(c&&!d?j(c.options,a):[]).filter(y=>y.is_tappable),f=c&&!d?oe(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!f&&h||_e(i.text,i.completedParams.length,r))return!1;let{rawQuery:S,completedParams:v}=O(i.text,i.completedParams),g=S.length<i.lastRawQuery.length,p=Math.abs(S.length-i.lastRawQuery.length),b=t&&S!==i.lastRawQuery;return g||p>=e||b?(this.doFetch(S,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function mo(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function z(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&mo(e)?e:n.ownerDocument??n}function A(n){return n.ownerDocument??n}function fo(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function kn(n){let e=z(n);return!fo(e)||typeof e.getSelection=="function"?null:e}function _n(n){let e=kn(n);if(!e)return null;let t=A(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function Nn(n,e){let t=n,i;try{i=t.getComposedRanges({shadowRoots:[e]})}catch{i=t.getComposedRanges(e)}return i.length>0?i[0]:null}function Ht(n){let t=z(n).getSelection?.();return t||(A(n).getSelection?.()??null)}function X(n){let e=Ht(n);if(!e||e.rangeCount===0)return null;let t=_n(n);if(t){let i=Nn(e,t);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function He(n){let e=Ht(n);if(!e||e.rangeCount===0)return null;let t=_n(n);if(!t)return e.getRangeAt(0);let i=Nn(e,t);if(!i)return null;let o=A(n).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function be(n,e,t){let i=Ht(n);if(!i)return null;if(kn(n))return i.collapse(e,t),i;let o=A(n).createRange();return o.setStart(e,t),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Be(n,e){let t=n?z(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var We=2,go="magicx-aia";function Fn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function ho(n){let e=A(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=t.getComputedStyle(i);if(o&&Fn(s.overflowX)||r&&Fn(s.overflowY))return i}if(i.classList.contains(go))return null;i=i.parentElement}return null}function $e(n){let e=He(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=ho(n);if(!t||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let r=o.left+t.clientLeft,s=r+t.clientWidth;i.right>s?t.scrollLeft+=i.right-s+We:i.left<r&&(t.scrollLeft-=r-i.left+We)}if(t.scrollHeight>t.clientHeight){let r=o.top+t.clientTop,s=r+t.clientHeight;i.bottom>s?t.scrollTop+=i.bottom-s+We:i.top<r&&(t.scrollTop-=r-i.top+We)}}var Wn='[contenteditable="false"]',bo="strong[data-param-id]",re;function yo(){if(re!==void 0)return re;let n=globalThis.Intl.Segmenter;if(!n)return re=null,null;try{re=new n(void 0,{granularity:"grapheme"})}catch{re=null}return re??null}function Ge(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Wn))return!0;t=t.parentNode}return!1}function qe(n){return A(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Ge(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ye(n){let e=qe(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Ue(n){let e=qe(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function k(n){let e=X(n);if(!e)return null;let t=e.node,i=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let o=t;if(Ge(o,n)&&o!==n)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=$n(o.childNodes[s],n);return r+Hn(o,n)}return t.nodeType!==Node.TEXT_NODE||Ge(t,n)?null:Hn(t,n)+i}function $n(n,e){if(n.nodeType===Node.TEXT_NODE)return Ge(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Wn))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=$n(o,e);return i}function Hn(n,e){let t=qe(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function I(n,e){let t=A(n),i=Math.max(0,Math.min(e,Ue(n))),o=qe(n),r=0,s=null,a=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(i<r+u){s=l,a=i-r;break}if(i===r+u){let m=o.nextNode();m?(s=m,a=0):(s=l,a=u);break}r+=u,c=l,l=o.nextNode()}let d=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===s.data.length?d.setStartAfter(u):d.setStart(s,a):d.setStart(s,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),be(n,d.startContainer,d.startOffset)&&(So(n,d,i),$e(n))}function Bn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(bo)??null;return i&&e.contains(i)?i:null}function So(n,e,t){let i=Bn(X(n)?.node??null,n);if(i&&i!==Bn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${i.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function Gn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=k(n);return i!==null&&t===`${i}:${e}`}function qn(n){return z(n).activeElement===n}function Ve(n){let e=k(n);return e==null?!1:e>=Ue(n)}function Ke(n,e){if(e<=0)return 0;let t=yo();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:r}of t.segment(i))r<e&&(o=r);return o}function G(n,e,t=[],i={}){let{rawQuery:o,completedParams:r}=O(n,e);return{query:n.trim(),raw_query:o,completed_params:ie(r,t),identified_params:ne(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Bt(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")?Ve(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Wt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?k(n):null}var Qe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=o(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=Bt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=w(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(w(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(t.activeDropdownIndex),f=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[f]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let m=Bt(e.target,t),f=!!t.editingParam;if(!m&&!f)break;e.preventDefault();let h=w(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),w(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),I(u,m);break}Bt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),w(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=Wt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),I(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=Wt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Wt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,r):a&&a(G(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((f,h)=>f.is_tappable?h:-1).filter(f=>f!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),m;if(u<0)m=e.shiftKey?d.length-1:0;else{let f=e.shiftKey?-1:1;m=(u+f+d.length)%d.length}this.store.set({activeDropdownIndex:d[m]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),I(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=o;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,t){let i=L(new Date),o=e.filteredOptions.findIndex(s=>N(s)===i);if(o>=0)return o;let r=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?r[r.length-1]:r[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.flat()}getEffectiveColumns(e){let t=Be(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let o=Be(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let r=getComputedStyle(o).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(o===t)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,o){let r=Be(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var Ye=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let r=Math.abs(i.query.length-o.query.length),s=i.query.length<o.query.length;if(t>1&&!s&&r<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(w(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=t(e.query,o.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(r)){this.commit(e,r,i);return}this.setSearch(e,"loading"),this.await(e,r,o.signal,i)}async await(e,t,i,o){let r;try{let s=await t;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||xo(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,t,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let r={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:t}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:t};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:r}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function xo(n){return n instanceof Error&&n.name==="AbortError"}var je=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((c,d)=>d!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=O(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:o.text,otherPills:r.map(d=>d.text)})}let a=[...s,o,...r],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 $t="/products/",Un="https://relative.invalid";function vo(n){if(!n)return;let e;try{e=new URL(n,`${Un}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Un?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Gt(n){let e=vo(n.item_url)??(n.handle?`${$t}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function ze(n){return(n?.items.matched??[]).map(Gt)}var Xe=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return ze(e)}async run(e,t,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>t.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,t);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],c=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(c)}catch(s){if(t.aborted||wo(s)||(this.logOnce(s),r()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function wo(n){return n instanceof Error&&n.name==="AbortError"}var Se="(max-width: 768px)";var Po="var(--aia-option-row-height, 37px)",Eo="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function Ut(n,e){return e?qt(1,Math.min(n,5)):qt(1,Math.min(n,4))}function qt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Po} + ${Eo})`}}function Ze(n,e){return!e&&n>=5}function et(n,e,t,i){if(!(!e&&n>=5&&To(t,i))){let s=Ut(n,e);return{...s,template:Je(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let r=6;return{...qt(2,3),template:Je(2),scrollHintIndices:n>r?[r-2,r-1]:[]}}function To(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function tt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let o=getComputedStyle(n),r=n.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function Je(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function nt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Se).matches}function Vn(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&c}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function xe(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function Kn(n){if(!n)return Lt();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Co(n){let e=fe(n);return e?gn(e):Lt()}function Qn(n,e){let t=Ln(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(P=>P.type!=="placeholder"),o=i[0],r=n.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" "),s=$(n.text,Math.min(n.filterBase,n.text.length),r),l=s===0&&_e(n.text,n.completedParams.length,r)?"":Y(n.text,s,n.filterInProgress),c=o?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,m,f,h;if(d&&n.editingParam&&n.editingAnchor!=null){let P=n.editingParam.id,_=n.completedParams.some(Wi=>Wi.id===P),pe=n.caretOffset??n.editingAnchor,dn=_?"":n.text.slice(n.editingAnchor,pe);m=dn.trim(),f=n.editingParam.options,h=n.editingParam.suggestionType,u=j(n.editingParam.options,dn)}else m=l.trim(),f=c,h=o?.type,u=j(c,l);let S=n.optionSearch,v=S!=null&&h!=null&&S.type===h;v&&S.status==="done"&&S.query===m&&(u=f);let g=v&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(P=>P.is_tappable));let b=n.editingIdentified,y=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:o,x=b?b.format:W(y),E=d&&w(x)?te(n.editingParam):null;E&&(x="date-range");let R=null,M=null;if(w(x)){let P=xe({...n,actionableSuggestions:i}),_=n.dateViewMonth;R=_&&_.key===P?{year:_.year,month:_.month}:b?Kn(b.iso):E?Kn(E.start):Co(n.editingParam?.text),u=Pe(R);let pe=n.pendingRangeStart;x==="date-range"&&pe&&pe.key===P&&(M=pe.iso)}let T=P=>p?P.is_tappable:!0,D;if(d){let P=n.editingParam?.options??[];D=n.editingParam!=null&&P.filter(T).length===0}else D=o!=null&&c.filter(T).length===0;let C=Vn({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||g,pillTapped:n.pillTapped,activePillHasNoOptions:D,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Ot=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:x,dateView:R,dateRangeStart:M,placeholderText:r,optionQuery:m,isSearchingOptions:g,isDropdownOpen:C,isActivePillSelected:Ot}}function it(n){return n.mode==="fresh"?Oo(n):Ao(n)}function Oo(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:r}=n,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),c=$(e,o,l),d=Y(e,c,r),u=oe(a.options,d);if(!u)return null;let m=u.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),h=f>=0?f:Math.max(0,e.length-u.text.length),S=h+u.text.length,v=e.slice(h,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function Ao(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:r}=n;if(t.some(b=>b.id===i.id))return null;let s=e.slice(o,r),a=oe(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=o+Math.max(0,c),u=d+a.text.length,m=e.slice(d,u),f=u<e.length&&e[u]===" "?u+1:u,h=e.length,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},v=t.length,g=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,g);if(y!==-1){if(y>=f){v=b;break}g=y+t[b].text.length}}let p=[...t];return p.splice(v,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function ot(n,e,t){let i=n.slice(0,e),o=n.slice(t),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:t-e+(r?1:0)}}var rt=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?ot(t.text,o,r):{text:t.text.slice(0,o)+e+t.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(g=>g.text!==e.text).map(g=>g.text)});let s=t.text.slice(0,o),a=t.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,m=u.length,f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=t.completedParams.findIndex(g=>g.id===i.id),S=t.completedParams.filter(g=>g.id!==i.id),v=h>=0?Math.min(h,S.length):S.length;S.splice(v,0,f),this.deps.store.set({text:u,completedParams:S,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=it({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 jn=33,zn=70,Xn=120,Jn=50,J="data-aia-placeholder-leaving",se=new WeakMap;function st(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Io(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Zn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function ei(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Zn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>ei(n,e),33+i)}function Yn(n,e){Zn(n,e,0),e.timer=setTimeout(()=>ei(n,e),33)}function ti(n,e){let t=se.get(n);if(e===""){t&&(st(t),se.delete(n)),n.removeAttribute(J),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Io(n)){t&&st(t),n.removeAttribute(J),se.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=t&&t.shown>0?t:null;if(t&&st(t),se.set(n,i),o){n.setAttribute(J,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(J),n.isConnected&&Yn(n,i)},170);return}n.removeAttribute(J),Yn(n,i)}function ni(n){let e=se.get(n);e&&(st(e),se.delete(n))}var Vt="https://ai-autocomplete.com";function at(n=Vt){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function lt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var ii=new WeakMap,oi=new WeakSet;function q(n,e,t){if(ii.set(n,t),oi.has(n))return;oi.add(n);let i=()=>ii.get(n),o=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&n.contains(s)?s:null};e.onClick&&n.addEventListener("click",r=>{let s=o(r.target);s&&e.onClick?.(s,i(),r)}),e.onEnter&&n.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,i())},!0),e.preventMousedown&&n.addEventListener("mousedown",r=>r.preventDefault())}function ae(n){return Number.parseInt(n.dataset.aiaIndex??"-1",10)}function U(n){n.offsetWidth}var Ro={selectedIso:null,selectedRange:null,rangeStart:null};function le(n){if(!w(n.activeFormatType))return Ro;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?ge(i,o):null,rangeStart:n.dateRangeStart}}let t=te(n.editingParam);return{selectedIso:t?null:Ee(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function dt(n){return n.pendingStart?ge(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function ct(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,o=n===t||i!=null&&(n===i.start||n===i.end),r=i!=null&&n>i.start&&n<i.end;return{selected:o,inRange:r}}var ri="data-aia-key";function V(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(ri);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);o.add(l);let c=i.get(l);c||(c=t.create(a,s),c.setAttribute(ri,l)),t.update?.(c,a,s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null),r.push(c)}for(let[s,a]of i)o.has(s)||a.remove();return r}function si(n,e){if(!e.interactive)return null;let t=e.options[ae(n)];return t?.is_tappable?t:null}var Do={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=si(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")&&si(n,e)&&e.callbacks.onHighlight(ae(n))}};function li(n,e,t,i,o,r,s,a=!0){let l=n.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){l?.remove();return}if(!l){l=ko(),n.appendChild(l),U(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}q(l,Do,{options:e,callbacks:s,interactive:a});let c=l.querySelector(".magicx-aia-datepicker-month");c&&(c.textContent=ve(o));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&Lo(d,e,t,i,r)}function Lo(n,e,t,i,o){let r=L(new Date),s=dt({pendingStart:o.rangeStart,highlightedIso:N(e[t]),selected:o.selectedRange});V(n,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>Mo(a),update:(a,l,c)=>{let d=N(l),u=ct(d,{selectedIso:o.selectedIso,range:s}),m=c===t&&l.is_tappable;a.id=`${i}-option-${c}`,a.dataset.aiaIndex=String(c),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",d!=null&&d<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",d!=null&&d===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function Mo(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=Te(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function ko(){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(ai("prev","Previous month","\u2039"),t,ai("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of me){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,i.appendChild(s)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),n.append(e,i,o),n}function ai(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.disabled=!0,i}var _o={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},di=[125,69];function ci(n,e){return e?1:n===0?.7:n===1?.4:.2}function ut(n,e,t,i,o=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),q(a,_o,{onSelectPill:i,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<di.length;l++){let c=di[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(ci(l,!1)),a.appendChild(d)}return}r?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();V(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.disabled=!0,c},update:(l,c,d)=>{let u=l,m=s&&d===t&&!r,f=["magicx-aia-pill"];o&&f.push("magicx-aia-pill--rounded"),r&&f.push("magicx-aia-pill--skeleton"),u.className=f.join(" "),u.style.width="",u.style.opacity=String(ci(d,m)),u.dataset.aiaPillIndex=String(d),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),U(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function Kt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ui=32;function Qt(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,i=e.deltaX||0;if(!t||Math.abs(i)>=Math.abs(t))return null;let o=n.scrollWidth-n.clientWidth;if(o<=1)return null;let r=n.scrollLeft,s=t;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=n.clientWidth),Math.max(0,Math.min(o,r+s))}function pt(n){let e=t=>{let i=Qt(n,t);i!==null&&(t.preventDefault(),n.scrollLeft=i)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var Yt=new WeakMap,No="Products";function pi(n,e,t,i,o,r="row"){let s=n.querySelector(".magicx-aia-products");if(e.length===0){s?.remove();return}if(!s){s=document.createElement("section"),s.className="magicx-aia-products",s.setAttribute("data-aia-products",""),s.setAttribute("role","group"),s.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=No;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),pt(c),s.append(l,c),n.appendChild(s)}s.setAttribute("data-aia-products-layout",r);let a=s.querySelector(".magicx-aia-products-row");if(a){V(a,e,{keyOf:l=>Fo(l),create:l=>Ho(l,i,o),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}}),U(a);for(let l of a.querySelectorAll("[data-aia-product]")){let c=Yt.get(l);c&&(Yt.delete(l),c())}}}function jt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Fo(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Ho(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.tabIndex=0;let o=document.createElement("span");if(o.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",o.appendChild(a)}else o.setAttribute("data-aia-product-placeholder","");i.appendChild(o);let r=document.createElement("span");if(r.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,r.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,r.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,r.appendChild(a)}return i.appendChild(r),Yt.set(i,()=>{n.url&&(i.href=n.url),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))})}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var mi=80,fi=150,gi=280,hi=16,mt="--aia-option-enter-delay";function ft(n,e,t,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,n)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/o));return Math.max(0,s-1-r)*80}function gt(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 F(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 de(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var zt={one:"item",other:"items"};function bi(n,e=zt){let t=de(n);if(t===null)return null;let i=typeof e=="string"?e:n===1?e.one:e.other;return i===""?t:`${t} ${i}`}function yi(n){return F(n.image_url)!==null}var Si="http://www.w3.org/2000/svg",Bo=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function Wo(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"],Go=/^[a-zA-Z0-9#.,%\s()-]+$/;function qo(n){let e=[];for(let t of $o){let i=n.getAttribute(t);i===null||!Go.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function xi(n){for(let e of Array.from(n.attributes))Wo(e.name,e.value)&&n.removeAttribute(e.name);qo(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Bo.has(t.localName)||t.namespaceURI!==Si?t.remove():xi(t)}else e.remove()}function ce(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!==Si||e.getElementsByTagName("parsererror").length>0?null:(xi(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function ht(n){return n.text}function Uo(n,e,t){let i=nt(),o=!t&&Ze(e,i)?tt(n):null,r=et(e,i,o?.rowWidths??null,o?.gridWidth??null);return n.style.gridTemplateColumns=r.template,n.style.setProperty("--aia-grid-max-height",r.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&r.scrollHintIndices.includes(a))}),r.cols}function vi(n,e){if(e.loading||!e.interactive)return null;let t=e.options[ae(n)];return t?.is_tappable?t:null}var Vo={itemSelector:"[data-aia-option]",onClick:(n,e)=>{let t=vi(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)=>{vi(n,e)&&e.onHighlight(ae(n))}};function wi(n,e,t,i,o,r,s,a="",l="below",c=!0,d=!0,u=!0,m=!0){let f=n.querySelector(".aia-grid");if(e.length===0){f?.remove();return}f||(f=document.createElement("div"),f.className="aia-grid magicx-aia-grid",f.setAttribute("data-scroll",""),f.style.setProperty("--aia-grid-min","250px"),f.style.setProperty("--aia-grid-max","1fr"),f.style.setProperty("--aia-grid-gap","0"),n.appendChild(f)),q(f,Vo,{options:e,onSelect:i,onHighlight:o,loading:s,interactive:m});let h=f.dataset.aiaGroup!==a;f.dataset.aiaGroup=a,Ko(f,e,t,r,s,{showIcons:c,showImages:d,showCounts:u});let S=Uo(f,e.length,s);Qo(f,e.length,S,s,l),h&&(f.scrollTop=0)}function Ko(n,e,t,i,o,r){let s=o?"1":"0",a=n.dataset.aiaGroup??"",{showIcons:l,showImages:c,showCounts:d}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=c?h=>F(h.image_url)??"":()=>"",f=d?h=>de(h.item_count)??"":()=>"";V(n,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${f(h)}\0${s}\0${a}`,create:(h,S)=>{let v=Yo(h,o,r);return o||(v.dataset.aiaEntering=""),v},update:(h,S,v)=>{let g=v===t&&!o;h.id=`${i}-option-${v}`,h.dataset.aiaIndex=String(v),h.setAttribute("aria-selected",String(g)),h.classList.toggle("magicx-aia-option--highlighted",g)}})}function Qo(n,e,t,i,o){for(let r of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(mt,`${ft(s,t,e,o)}ms`)}delete r.dataset.aiaEntering}}function Yo(n,e,{showIcons:t,showImages:i,showCounts:o}){let r=document.createElement("div");r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),e&&r.setAttribute("data-aia-loading",""),r.tabIndex=e||!n.is_tappable?-1:0;let s=["magicx-aia-option"];n.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),r.className=s.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=i?F(n.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.setAttribute("aria-hidden","true");let f=document.createElement("img");f.setAttribute("alt",""),f.setAttribute("loading","lazy"),f.setAttribute("decoding","async"),f.setAttribute("referrerpolicy","no-referrer"),f.setAttribute("draggable","false"),f.onerror=()=>{f.hidden=!0},f.src=l,m.appendChild(f),a.appendChild(m),r.dataset.aiaImage=""}let c=!l&&t&&n.icon_svg?ce(n.icon_svg):null;if(c){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=c,a.appendChild(m),n.icon&&(r.dataset.aiaIcon=n.icon)}let d=document.createElement("span");if(d.className="magicx-aia-option-text",d.textContent=ht(n),a.appendChild(d),n.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=n.tag,a.appendChild(m)}let u=o?de(n.item_count):null;if(u!==null){let m=document.createElement("span");m.className="magicx-aia-option-count",m.textContent=u,a.appendChild(m),r.dataset.aiaItemCount=String(n.item_count)}return r.appendChild(a),r}var Jt="magicx-aia-scroll-arrow",Zt="data-aia-scroll-arrow",Z="data-aia-visible",en=1e3,tn=160,nn="--aia-scroll-arrow-bottom",on="Scroll down for more options",jo="[data-aia-products-label]",zo=4,Xo=8,Jo=240;function Zo(n,e,t,i){let o=n.scrollTop,r=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!r||s||Xt(n)){n.scrollTop=o+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/Jo),u=1-(1-d)*(1-d);n.scrollTop=o+e*u,d<1?r.call(t,c):i()};r.call(t,c)}function er(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Pi(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Jt,e.setAttribute(Zt,""),e.setAttribute("aria-label",on),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(er(n)),e}function tr(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Xt(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function bt({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1;t.disabled=!0;let r=null,s=null,a=null,l=null,c=p=>{if(p){if(t.hasAttribute(Z))return;if(t.setAttribute(Z,""),t.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),Xt(e)){t.disabled=!1;return}l=setTimeout(()=>{l=null,!o&&t.hasAttribute(Z)&&(t.disabled=!1)},en)}else t.removeAttribute(Z),t.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,t.disabled=!0},d=p=>{let b=0,y=p;for(;y&&y!==n;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=n.querySelector(jo),b;if(p){let y=d(p)+p.offsetHeight/2;b=n.clientHeight-y-t.offsetHeight/2}else{let y=d(e),x=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;b=n.clientHeight-(y+e.offsetHeight)+(x>0?0:Xo)}t.style.setProperty(nn,`${Math.max(0,Math.round(b))}px`)},m=()=>{if(o||s!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,b=e.scrollHeight-e.clientHeight-e.scrollTop;c(!p&&b>zo)},f=()=>{if(o)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,c(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=Xt(e)?0:gt(b,tr(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{o||s!==null||(c(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},tn))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),v=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-p);Zo(e,b,i,h)};t.addEventListener("mousedown",S),t.addEventListener("click",v);let g=null;return i&&typeof i.ResizeObserver=="function"&&(g=new i.ResizeObserver(()=>{u(),m()}),g.observe(e)),f(),{update:f,destroy(){o||(o=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,t.disabled=!0,e.removeEventListener("scroll",h),t.removeEventListener("mousedown",S),t.removeEventListener("click",v),g?.disconnect(),t.removeAttribute(Z),t.setAttribute("aria-hidden","true"))}}}var nr=[159,119,164];function St(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}var yt=new WeakMap;function ir(n,e){let t=yt.get(n);if(t||(t={button:Pi(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),yt.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=bt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function rn(n){let e=yt.get(n);e&&(e.controller?.destroy(),yt.delete(n))}function xt(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:m}=e,f=s.length>0,h=a&&f,S=t.length>0,v=e.products.length>0,g=o&&(S||h||r||v);if(g?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),r?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!g){jt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let p=n.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),n.appendChild(p));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=h||r&&a||b,x=p.querySelector(".magicx-aia-pill-bar");if(y){x||(x=document.createElement("div"),x.className="magicx-aia-pill-bar aia-cluster",x.setAttribute("data-nowrap",""),x.setAttribute("data-aia-pillbar",""),p.insertBefore(x,p.firstChild));let P=x.querySelector(".magicx-aia-pill-scroll");P||(P=document.createElement("span"),P.className="magicx-aia-pill-scroll",P.setAttribute("data-aia-pill-scroll",""),x.insertBefore(P,x.firstChild)),ut(P,a?s:[],0,u,!0,r&&a,l),sr(x,b,r||e.skipDisabled,s[0],m)}else x&&x.remove();let E=e.suggestions[0],R=E?`${E.type} ${E.text}`:"",M=w(e.formatType),T=M&&!r;wi(p,M?[]:t,i,c,d,e.listboxId,r,R,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),ir(n,p.querySelector(".aia-grid")),li(p,T?t:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let D=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||M)){if(!D){D=document.createElement("div"),D.className="magicx-aia-skeleton-bars",D.setAttribute("data-aia-skeleton-bars","");for(let P of nr){let _=document.createElement("span");_.className="magicx-aia-skeleton-bar",_.style.width=`${P}px`,D.appendChild(_)}p.appendChild(D)}}else D&&D.remove();pi(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),jt(n,!0);let C=p.querySelector(".magicx-aia-footer")??lr(),Ot=i>=0&&!!t[i]?.is_tappable;ar(C,lt(Ot,e.isInputEmpty)),C.isConnected||p.appendChild(C),or(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function or(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}var rr={itemSelector:".magicx-aia-skip",onClick:(n,e)=>{e.loading||e.onSkip()}};function sr(n,e,t,i,o){q(n,rr,{onSkip:o,loading:t});let r=n.querySelector(".magicx-aia-skip");if(!e){r?.remove();return}r||(r=document.createElement("button"),r.type="button",r.tabIndex=-1,r.className="magicx-aia-skip",r.setAttribute("data-aia-skip",""),r.textContent="skip",r.disabled=!0,n.appendChild(r),U(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=t}function ar(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function lr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=at(),r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(t,r),n.append(e),n}function Ei(n,e){let t=St(e.listboxId);return n.appendChild(t),{dropdown:t}}function sn(n,e,t){let i=le(e);xt(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:H(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:o=>t.store.set({isFocused:o})})}var dr=6,cr=.3;function Ti(n){return n<=0?"0px":`${(-Math.min(cr,2*dr/n)).toFixed(3)}px`}function vt(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",ti(e,c?r:"");let d=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?F(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(d===u&&(i??"")===m&&(o??"")===f)return;if(d===u){e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";for(let p of e.querySelectorAll("strong[data-param-id]")){let b=p.dataset.paramId,y=p.dataset.seg==="completed"&&b===i;p.classList.toggle("magicx-aia-shimmer-revealed",y),p.classList.toggle("magicx-aia-shimmer-sweep",y),p.classList.toggle("magicx-aia-segment--editing",b===o)}return}let h=s?k(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let S=A(e),v=S.createDocumentFragment(),g=0;for(let p of t)if(g+=p.value.length,p.type==="completed"){let b=S.createElement("strong");b.dataset.seg="completed",b.dataset.paramId=p.param.id;let y=p.param.id===i,x=p.param.id===o,E=["magicx-aia-segment","magicx-aia-segment--completed"];y&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&E.push("magicx-aia-segment--editing"),b.className=E.join(" "),b.style.letterSpacing=Ti(p.value.length);let R=l?F(p.param.image_url):null;if(R){let T=S.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${R}")`),b.appendChild(T),b.dataset.aiaImage=""}let M=!R&&a&&p.param.icon_svg?ce(p.param.icon_svg):null;if(M){let T=S.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=M,b.appendChild(T),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),v.appendChild(b)}else if(p.type==="identified"){let b=S.createElement("strong");b.dataset.seg="identified",b.dataset.paramId=p.param.id;let y=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===o&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=Ti(p.value.length),b.textContent=p.value,v.appendChild(b)}else v.appendChild(S.createTextNode(p.value));e.replaceChildren(v),e.dataset.aiaTextLength=String(g),h!=null?I(e,Math.max(0,Math.min(h,g))):s&&qn(e)&&I(e,g)}var ur='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Ci(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=ur,n}function pr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Oi(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ai(n,e){let{listboxId:t}=e,i=St(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",pr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=Ci(),o.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",""),o.appendChild(c));let d=new AbortController,{signal:u}=d,m=!1,f=0,h=()=>{let g=ye(s),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=X(s)?.node??null;if(!g||!s.contains(g))return null;let y=(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&Gn(s,y)?null:y};if(o.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(f=performance.now(),h(),e.handleCaretAfterInput(k(s)))},{signal:u}),A(s).addEventListener("selectionchange",()=>{let g=X(s);if(!g||!s.contains(g.node))return;let p=g.collapsed?S():null,b=e.store.get(),y=b.editingParam?.id??b.editingIdentified?.id??null;if(p&&p!==y){e.startEditingParam(p);return}performance.now()-f<50||e.handleCaretMove(k(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",g=>{let p=g,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){g.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(y)&&g.preventDefault()}},{signal:u}),s.addEventListener("paste",g=>{g.preventDefault();let p=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=A(s),y=He(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let x=b.createTextNode(p);y.insertNode(x),y.setStartAfter(x),be(s,y.startContainer,y.startOffset),h()},{signal:u}),s.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",g=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(G(p.text,p.completedParams,p.skippedParams,{identifiedParams:p.identifiedParams,isReady:p.isReady,customFields:p.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let g=X(s);(!g||!s.contains(g.node))&&be(s,s,0)}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>Oi(s,a));g.observe(s),d.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function an(n,e,t){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let g=!!e.text||e.completedParams.length>0;s.disabled=!g}let m=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==m;if(vt({input:i,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 g=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;g||e.actionableSuggestions.length>0?ut(o,e.actionableSuggestions,0,l,!1,g,e.isActivePillSelected):Kt(o)}else Kt(o);Oi(i,o),f?(i.focus(),I(i,e.caretOffset??e.text.length)):e.isFocused&&ye(i)!==e.text&&I(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:H(e.editingIdentified.type),required:!0,options:[]}:null,S=h??e.actionableSuggestions[0],v=le(e);xt(r,{suggestions:S?[{...S,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:g=>d.set({activeDropdownIndex:g}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:g=>d.set({isFocused:g})})}function Ii(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),r=o.length===0&&n.text.length===0,s=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=Tn(o,e.text);a>0&&(o=o.slice(0,o.length-a));let l=o.length>0&&o[o.length-1]!==" ",c=`${o}${l?" ":""}${e.text} `,d=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,value:e.value,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(S=>S.text!==e.text).map(S=>S.text)},consumedSuggestion:t,remainingActionable:h}}function wt(n){let e=n,t=new Set,i=[],o=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},i.push([e,a]),!o){o=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let m of t)m(d,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(t.add(r),()=>{t.delete(r)})}}function Ri(n,e){let t,i,o=r=>(r!==t&&(t=r,i=e(r)),i);return{get:()=>{let r=n.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...o(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let l={...a,...o(a)},c={...s,...o(s)};r(c,l)})}}var ln=new WeakSet,Di=new WeakMap;function Mi(n){return n.nodeType===Node.DOCUMENT_NODE}function mr(n){return Mi(n)?n:n.ownerDocument}function fr(n){let e=Di.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(_i),Di.set(n,i),i)}catch{return null}}function Li(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=_i,e.appendChild(t)}function ki(n){if(typeof document>"u")return;let e=n??document;if(ln.has(e))return;let t=mr(e);if(Mi(e)){let r=e.head??e.documentElement;if(!r)return;Li(t,r),ln.add(e);return}let i=fr(t),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):Li(t,e),ln.add(e)}var _i=`.aia-stack {
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--aia-stack-space, 0.5rem);
@@ -110,8 +110,9 @@
110
110
  10px the two sides would diverge; flooring both keeps them together. */
111
111
  padding: 12px 16px 12px max(10px, var(--aia-content-inset-left, 16px));
112
112
  border: 1px solid var(--aia-border, #b0b0b0);
113
- border-radius: 20px;
113
+ border-radius: 10px;
114
114
  background: var(--aia-surface, #ffffff);
115
+ /* Flat by default; consumers can set --aia-shadow for elevation. */
115
116
  box-shadow: var(--aia-shadow, none);
116
117
  overflow: hidden;
117
118
  display: flex;
@@ -438,8 +439,9 @@
438
439
  frosted-glass look with data-aia-surface="glass". */
439
440
  background: var(--aia-surface, #ffffff);
440
441
  border: 1px solid var(--aia-dropdown-border, rgba(231, 231, 231, 0.5));
441
- border-radius: 18px;
442
- box-shadow: var(--aia-dropdown-shadow, 0 8px 12px rgba(0, 0, 0, 0.05));
442
+ border-radius: 9px;
443
+ /* Flat by default; consumers can set --aia-dropdown-shadow for elevation. */
444
+ box-shadow: var(--aia-dropdown-shadow, none);
443
445
  }
444
446
 
445
447
  .magicx-aia-dropdown[data-aia-surface="glass"] {
@@ -454,8 +456,7 @@
454
456
  hsla(0, 0%, 100%, 0.15) 0px -1.6px 0px -1.6px inset,
455
457
  hsla(0, 0%, 100%, 0.3) 0px 1.6px 0px 0px inset,
456
458
  hsla(0, 0%, 100%, 0.3) 1.6px 0px 0px 0px inset,
457
- inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05),
458
- hsla(0, 0%, 0%, 0.08) 0px 0px 30px 2px;
459
+ inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05);
459
460
  backdrop-filter: blur(30px);
460
461
  }
461
462
 
@@ -866,6 +867,13 @@
866
867
  opacity: 1;
867
868
  }
868
869
 
870
+ /* Visible but not yet armed: the arrow is disabled for the length of its
871
+ fade-in (scrollArrow.ts \u2014 a native button appearing clickable cancels an
872
+ iOS tap in flight). No pointer cursor over a button that takes no click. */
873
+ .magicx-aia-scroll-arrow:disabled {
874
+ cursor: default;
875
+ }
876
+
869
877
  /* The chevron's size and paint by class \u2014 see .magicx-aia-submit svg. */
870
878
  .magicx-aia-scroll-arrow svg {
871
879
  width: 14px;
@@ -898,7 +906,7 @@
898
906
  badge sits as far from the right edge as it does from the bottom \u2014 12px
899
907
  both ways (dropdown padding 10 + pill 2 down, dropdown padding 8 + pill 4
900
908
  across). */
901
- padding: var(--aia-footer-gap, 8px) 0 0 8px;
909
+ padding: var(--aia-footer-gap, 12px) 0 0 8px;
902
910
  /* The fade itself lives in appearance.css, on the footer's background.
903
911
  Paints above the rows it covers: option content sits at z-index 2 (see
904
912
  .magicx-aia-option-content) in this same stacking context, so anything
@@ -1284,9 +1292,14 @@
1284
1292
  }
1285
1293
  }
1286
1294
 
1295
+ /* Starts a hair above zero on purpose. iOS reads an element at exactly
1296
+ \`opacity: 0\` as hidden, and a clickable element (a pill is a native button,
1297
+ a chip sits in the editable) going from hidden to visible while a finger is
1298
+ down cancels that tap \u2014 see delegatedEvents.ts. 0.01 is invisible and never
1299
+ "hidden". */
1287
1300
  @keyframes magicx-aia-fadeIn {
1288
1301
  from {
1289
- opacity: 0;
1302
+ opacity: 0.01;
1290
1303
  }
1291
1304
  }
1292
1305
 
@@ -1324,13 +1337,13 @@
1324
1337
  SuggestionItem selection. The 9px/10px inset is the item's own padding. */
1325
1338
  border-radius: 8px;
1326
1339
  padding: 8px 10px;
1327
- /* Entrance: fade in while rising into place, each row a beat after the one
1328
- before it (--aia-option-enter-delay is set inline per row from the core's
1329
- optionEnterDelayMs). The fade is here; the rise is on the inner content
1330
- (see the overflow note above). The durations and distance mirror
1331
- OPTION_ENTER_* in derive/optionsEntrance.ts \u2014 change both together. */
1332
- animation: magicx-aia-optionFadeIn 150ms ease-out both;
1333
- animation-delay: var(--aia-option-enter-delay, 0ms);
1340
+ /* No entrance animation on the row itself \u2014 deliberately. The row is the
1341
+ tappable element, and iOS Safari drops a tap on a scripted-clickable
1342
+ element (a div with a click handler; a native button is exempt) whose
1343
+ own opacity is mid-animation \u2014 its tap-or-hover pass counts the change
1344
+ as content moving under the finger, fires only the hover events (the
1345
+ row highlights) and never the click. Both halves of the entrance run
1346
+ on the inner content instead (next rule). */
1334
1347
  }
1335
1348
 
1336
1349
  @keyframes magicx-aia-optionFadeIn {
@@ -1348,9 +1361,17 @@
1348
1361
  .magicx-aia-option-content {
1349
1362
  position: relative;
1350
1363
  z-index: 2;
1351
- /* The entrance rise (the cell above keeps the fade). Inherits the cell's
1352
- per-row delay through the custom property. */
1353
- animation: magicx-aia-optionRiseIn 280ms cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
1364
+ /* The entrance: fade in while rising into place, each row a beat after the
1365
+ one before it (--aia-option-enter-delay is set inline per row from the
1366
+ core's optionEnterDelayMs). Both run here, on the inner content, never on
1367
+ the row: the rise because a transformed cell extends the grid's
1368
+ scrollable area (see the overflow note on the row), the fade because iOS
1369
+ Safari drops a tap on a tappable element whose own opacity is animating
1370
+ (see the row's own comment). The durations and distance mirror
1371
+ OPTION_ENTER_* in derive/optionsEntrance.ts \u2014 change both together. */
1372
+ animation:
1373
+ magicx-aia-optionRiseIn 280ms cubic-bezier(0.25, 0.46, 0.45, 0.94) both,
1374
+ magicx-aia-optionFadeIn 150ms ease-out both;
1354
1375
  animation-delay: var(--aia-option-enter-delay, 0ms);
1355
1376
  }
1356
1377
 
@@ -1788,15 +1809,14 @@
1788
1809
  :where(.magicx-aia[data-mode="light"]) {
1789
1810
  --aia-surface: var(--aia-primitive-neutral-1000);
1790
1811
  --aia-border: rgba(17, 24, 39, 0.14); /* subtle slate hairline (off-palette) */
1791
- /* Elevation for the input container (.magicx-aia-input-wrapper). */
1792
- --aia-shadow:
1793
- inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 1px 2px rgba(16, 24, 40, 0.05),
1794
- 0 8px 24px rgba(16, 24, 40, 0.08);
1812
+ /* Flat by default \u2014 no elevation on the input container. Consumers set
1813
+ --aia-shadow to add one. */
1814
+ --aia-shadow: none;
1795
1815
  /* Half-strength stroke: neutral-900 (was #e5e7eb \u2014 snapped to palette,
1796
1816
  \u03942) at 50% alpha over the surface, so the hairline lands exactly
1797
1817
  halfway between its old value and the white behind it. */
1798
1818
  --aia-dropdown-border: var(--aia-primitive-neutral-900-a50);
1799
- --aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.05);
1819
+ --aia-dropdown-shadow: none; /* flat by default */
1800
1820
  /* Suggestion pills (Figma "ParamPill"): transparent fill, no visible border;
1801
1821
  per-pill opacity via getPillOpacity. --aia-pill-bg is retained for
1802
1822
  consumer overrides but the default ParamPill no longer paints a fill. */
@@ -1844,15 +1864,13 @@
1844
1864
  :where(.magicx-aia[data-mode="dark"]) {
1845
1865
  --aia-surface: var(--aia-primitive-neutral-0);
1846
1866
  --aia-border: var(--aia-primitive-neutral-500);
1847
- /* Elevation for the input container (.magicx-aia-input-wrapper) \u2014 tuned for
1848
- dark surfaces: a faint top highlight + deeper ambient shadows. */
1849
- --aia-shadow:
1850
- inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px rgba(0, 0, 0, 0.2),
1851
- 0 8px 24px rgba(0, 0, 0, 0.25);
1867
+ /* Flat by default \u2014 no elevation on the input container. Consumers set
1868
+ --aia-shadow to add one. */
1869
+ --aia-shadow: none;
1852
1870
  /* Half-strength stroke \u2014 neutral-400 (was #484848 \u2014 snapped to palette,
1853
1871
  \u03942) at 50% alpha; see the light-mode note above. */
1854
1872
  --aia-dropdown-border: var(--aia-primitive-neutral-400-a50);
1855
- --aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.05);
1873
+ --aia-dropdown-shadow: none; /* flat by default */
1856
1874
  /* Suggestion pills (Figma "ParamPill"): transparent fill, no visible border. */
1857
1875
  --aia-pill-bg: var(--aia-primitive-neutral-750);
1858
1876
  --aia-pill-color: var(--aia-primitive-neutral-700);
@@ -1912,7 +1930,7 @@
1912
1930
  (the kbd is shorter and centers against it). The band derives from it, so
1913
1931
  restyling the badge's height keeps the overlap in step. */
1914
1932
  --aia-footer-row-height: 23px;
1915
- --aia-footer-band: calc(var(--aia-footer-gap, 8px) + var(--aia-footer-row-height, 23px));
1933
+ --aia-footer-band: calc(var(--aia-footer-gap, 12px) + var(--aia-footer-row-height, 23px));
1916
1934
  --aia-grid-scroll-bottom: var(--aia-footer-band);
1917
1935
  --aia-grid-overlap-bottom: calc(-1 * (var(--aia-footer-band) + 8px));
1918
1936
  /* How far above the band the fade starts. */
@@ -2020,7 +2038,7 @@
2020
2038
  /* The footer now sits on top of the list, so its breathing room flips to the
2021
2039
  bottom edge \u2014 the side the option rows scroll under. */
2022
2040
  :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] [data-aia-footer] {
2023
- padding: 0 0 var(--aia-footer-gap, 8px) 8px;
2041
+ padding: 0 0 var(--aia-footer-gap, 12px) 8px;
2024
2042
  }
2025
2043
 
2026
2044
  /* ...and the fade runs the other way, out of the footer and down into the list. */
@@ -2050,5 +2068,5 @@
2050
2068
  background: var(--aia-surface, #ffffff);
2051
2069
  }
2052
2070
  }
2053
- `;var xt=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(o){return this.report(e,o,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var vt=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>t(...s);this.keys.set(o,i);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...t),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var wt=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}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 ae=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function ir(n){return(n??Ae).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function or(n){return pe(n)?`Bearer ${await Ie(n).getToken()}`:De(n)}async function Ai(n){try{let e=ir(n.apiConfig?.endpoint),t=Re(n.apiConfig),i=await or(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var rr="newParam",Ii="suggestionRemoval",sr="selectionAnimation",ar=650,lr=0;function dr(){return`:ac-${++lr}:`}var Ri=170;function Di(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Pt=class{constructor(e,t={}){this.inputStore=St(Di());this._listboxId=dr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new wt;this.boundary=new xt;this.subscriberCount=0;this.emitter=new vt(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=wi(this.inputStore,i=>$n(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Ke(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new nt({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Ye(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Ve(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.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,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:(i.options??[]).filter(s=>s.text!==o.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new Ue(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:r,invalid:s}=Me(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let r=i.editingIdentified;if(!r||i.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===r.anchor&&l.value===r.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...r,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let o=i.pendingRangeStart;!o||o.key===he(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let r=i.pendingSpan;if(!r||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let s=r.anchor;if(i.text!==o.text){let l=En(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||wn(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(Ci(this.opts.styleRoot??Y(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...Di(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.optionSource.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(zn(this.domRefs.input),Jt(this.domRefs.dropdown)),this.dropdownRefs&&Jt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let o=t;if(t+=i.value.length,i.type!=="text"&&e>o&&e<=t)return{kind:i.type,param:i.param,start:o,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:o,end:r}=t;if(e===r){let{text:l,removed:c}=tt(i,o,r);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>o?Math.max(o,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=qe(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),I(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let o=W(i);if(!w(o))return!1;let r=V(i.text),s=o==="date-range"||r?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:r?r.start:Ee(i),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!w(t.activeFormatType)||!t.dateView)return;let i=Se(t.dateView,e);this.store.set({dateViewMonth:{...i,key:he(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],r=i.slice(1),s=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.text}]}}),r.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return G(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showOptionImages!==void 0||e.showOptionCounts!==void 0||e.productsLayout!==void 0||e.showChipIcons!==void 0||e.showChipImages!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.activeFormatType==="date-range"){let o=N(e);if(o){let r=t.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:he(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(mn(r,o));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=vi(t,e);if(i){if(this.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:w(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Ii),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(Ii,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},Ri)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(sr,()=>this.store.set({inSelectionAnimation:!1}),Ri)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let i=this.resolveSource();Ai({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new ae(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},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.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=xi(this.container,t);let i=()=>{this.domRefs&&en(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),en(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=hi(this.container,t);let i=()=>{this.dropdownRefs&&Zt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Zt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(ge),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(rr,()=>this.store.set({newParamId:null}),ar)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=On(e,t.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=$(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=vn(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(r=>r.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);Q(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=O(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=t.text.slice(0,i.anchor),r=t.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=r.length===0||r[0]!==" "?`${s} `:s,c=o+l+r,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:H(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(p=>p.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(w(t.activeFormatType))return;let i=et({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,DATE_RANGE_META_END,DATE_RANGE_META_START,DEFAULT_OPTION_COUNT_UNIT,ModeController,OPTIONS_GRID_MOBILE_QUERY,OPTION_ENTER_DELAY_VAR,OPTION_ENTER_FADE_MS,OPTION_ENTER_RISE_MS,OPTION_ENTER_RISE_PX,OPTION_ENTER_STAGGER_MS,PLACEHOLDER_FADE_OUT_MS,PLACEHOLDER_LEAVING_ATTR,PLACEHOLDER_SWAP_GAP_MS,PLACEHOLDER_TYPE_MS,PLACEHOLDER_WORD_PAUSE_MS,PRODUCT_PATH_PREFIX,PRODUCT_ROW_PX_PER_LINE,RANGE_SEPARATOR,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,computeOptionsGridLayout,createStore,cursorIsAtEnd,dateCellMarks,dateSelectionFor,extractPlainText,formatAbsoluteDate,formatDate,formatDateRange,formatOptionCount,getCursorOffset,getFooterHint,identifiedParamLabel,isCalendarFormat,isOptionsGridMobileViewport,isoDate,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionCountLabel,optionEnterDelayMs,optionHasImage,optionImageSrc,optionLabel,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,parseLooseDateRange,plainTextLength,planOptionsGrid,previousGraphemeBoundary,productFromMatchedItem,productRowWheelTarget,productsFromCustomFields,renderEditableContent,resolveFormatType,resolveIdentifiedDate,sanitizeOptionIconSvg,scrollCaretIntoView,selectedIsoFromText,selectedRangeFor,setCursorOffset,toWireIdentifiedParams,visibleDateRange,withSkippedParams});
2071
+ `;var Pt=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(o){return this.report(e,o,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var Et=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>t(...s);this.keys.set(o,i);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...t),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Tt=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}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 ue=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function gr(n){return(n??De).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function hr(n){return he(n)?`Bearer ${await Le(n).getToken()}`:ke(n)}async function Ni(n){try{let e=gr(n.apiConfig?.endpoint),t=Me(n.apiConfig),i=await hr(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var br="newParam",Fi="suggestionRemoval",yr="selectionAnimation",Sr=650,xr=0;function vr(){return`:ac-${++xr}:`}var Hi=170;function Bi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Ct=class{constructor(e,t={}){this.inputStore=wt(Bi());this._listboxId=vr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Tt;this.boundary=new Pt;this.subscriberCount=0;this.emitter=new Et(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Ri(this.inputStore,i=>Qn(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new je(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new rt({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Xe(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Ye(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Fe(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:(i.options??[]).filter(s=>s.text!==o.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new Qe(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:r,invalid:s}=Ne(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let r=i.editingIdentified;if(!r||i.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===r.anchor&&l.value===r.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...r,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let o=i.pendingRangeStart;!o||o.key===xe(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let r=i.pendingSpan;if(!r||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let s=r.anchor;if(i.text!==o.text){let l=Rn(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||An(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(ki(this.opts.styleRoot??z(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...Bi(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.optionSource.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(ni(this.domRefs.input),rn(this.domRefs.dropdown)),this.dropdownRefs&&rn(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let o=t;if(t+=i.value.length,i.type!=="text"&&e>o&&e<=t)return{kind:i.type,param:i.param,start:o,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:o,end:r}=t;if(e===r){let{text:l,removed:c}=ot(i,o,r);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>o?Math.max(o,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=Ke(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),I(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let o=W(i);if(!w(o))return!1;let r=Q(i.text),s=o==="date-range"||r?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:r?r.start:Oe(i),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!w(t.activeFormatType)||!t.dateView)return;let i=we(t.dateView,e);this.store.set({dateViewMonth:{...i,key:xe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],r=i.slice(1),s=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.text}]}}),r.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return G(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showOptionImages!==void 0||e.showOptionCounts!==void 0||e.productsLayout!==void 0||e.showChipIcons!==void 0||e.showChipImages!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.activeFormatType==="date-range"){let o=N(e);if(o){let r=t.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:xe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Sn(r,o));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Ii(t,e);if(i){if(this.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:w(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Fi),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(Fi,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},Hi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(yr,()=>this.store.set({inSelectionAnimation:!1}),Hi)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let i=this.resolveSource();Ni({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new ue(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},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.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Ai(this.container,t);let i=()=>{this.domRefs&&an(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),an(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Ei(this.container,t);let i=()=>{this.dropdownRefs&&sn(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),sn(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(Se),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(br,()=>this.store.set({newParamId:null}),Sr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=Mn(e,t.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=$(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=On(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(r=>r.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);j(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=O(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=t.text.slice(0,i.anchor),r=t.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=r.length===0||r[0]!==" "?`${s} `:s,c=o+l+r,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:H(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:O(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(m=>m.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(w(t.activeFormatType))return;let i=it({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,DATE_RANGE_META_END,DATE_RANGE_META_START,DEFAULT_OPTION_COUNT_UNIT,ModeController,OPTIONS_GRID_MOBILE_QUERY,OPTION_ENTER_DELAY_VAR,OPTION_ENTER_FADE_MS,OPTION_ENTER_RISE_MS,OPTION_ENTER_RISE_PX,OPTION_ENTER_STAGGER_MS,PLACEHOLDER_FADE_OUT_MS,PLACEHOLDER_LEAVING_ATTR,PLACEHOLDER_SWAP_GAP_MS,PLACEHOLDER_TYPE_MS,PLACEHOLDER_WORD_PAUSE_MS,PRODUCT_PATH_PREFIX,PRODUCT_ROW_PX_PER_LINE,RANGE_SEPARATOR,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,computeOptionsGridLayout,createStore,cursorIsAtEnd,dateCellMarks,dateSelectionFor,extractPlainText,formatAbsoluteDate,formatDate,formatDateRange,formatOptionCount,getCursorOffset,getFooterHint,identifiedParamLabel,isCalendarFormat,isOptionsGridMobileViewport,isoDate,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionCountLabel,optionEnterDelayMs,optionHasImage,optionImageSrc,optionLabel,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,parseLooseDateRange,plainTextLength,planOptionsGrid,previousGraphemeBoundary,productFromMatchedItem,productRowWheelTarget,productsFromCustomFields,renderEditableContent,resolveFormatType,resolveIdentifiedDate,sanitizeOptionIconSvg,scrollCaretIntoView,selectedIsoFromText,selectedRangeFor,setCursorOffset,toWireIdentifiedParams,visibleDateRange,withSkippedParams});
2054
2072
  //# sourceMappingURL=index.js.map