@magicx-eng/ai-autocomplete-vanilla 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Fe=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Wt=(n,e)=>{for(var t in e)Fe(n,t,{get:e[t],enumerable:!0})},Qt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gt(e))!qt.call(n,r)&&r!==t&&Fe(n,r,{get:()=>e[r],enumerable:!(i=Ut(e,r))||i.enumerable});return n};var jt=n=>Qt(Fe({},"__esModule",{value:!0}),n);var Wn={};Wt(Wn,{AIAutocomplete:()=>Re,ATTRIBUTION_URL:()=>qe,ModeController:()=>V,OPTIONS_GRID_MOBILE_QUERY:()=>z,SKIPPED_PARAM_TEXT:()=>$e,WEEKDAY_LABELS:()=>q,addMonths:()=>J,buildAttributionUrl:()=>Ee,buildDateOptions:()=>Z,buildQuery:()=>C,buildSubmitResult:()=>K,cellDay:()=>ee,cellIso:()=>L,computeOptionsGridLayout:()=>ye,createStore:()=>ke,cursorIsAtEnd:()=>fe,extractPlainText:()=>Y,formatDate:()=>He,getCursorOffset:()=>A,getFooterHint:()=>Te,isOptionsGridMobileViewport:()=>ve,isoDate:()=>T,monthLabel:()=>X,optionsGridTemplateColumns:()=>Se,parseDate:()=>W,parseLooseDate:()=>Q,plainTextLength:()=>me,previousGraphemeBoundary:()=>ge,renderEditableContent:()=>De,resolveFormatType:()=>D,resolveIdentifiedDate:()=>ne,selectedIsoFromText:()=>F,setCursorOffset:()=>E,withSkippedParams:()=>H});module.exports=jt(Wn);var G=["January","February","March","April","May","June","July","August","September","October","November","December"],q=["S","M","T","W","T","F","S"],Ze="aiaDate",et="aiaDay",Xe=n=>String(n).padStart(2,"0");function T(n){return`${n.getFullYear()}-${Xe(n.getMonth()+1)}-${Xe(n.getDate())}`}function He(n){return`${G[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function W(n){if(!n)return null;let e=/^\s*([A-Za-z]+)\s+(\d{1,2})\s+(\d{4})\s*$/.exec(n);if(!e)return null;let t=G.findIndex(a=>a.toLowerCase()===e[1].toLowerCase());if(t<0)return null;let i=Number(e[2]),r=Number(e[3]),o=new Date(r,t,i);return o.getMonth()!==t||o.getDate()!==i?null:o}function X(n){return`${G[n.month]} ${n.year}`}function Be(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function tt(n){return{year:n.getFullYear(),month:n.getMonth()}}function J(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Je(){return{text:"",is_tappable:!1,kind:null}}function Z(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let r=0;r<e;r++)i.push(Je());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:He(o),is_tappable:!0,kind:null,metadata:{[Ze]:T(o),[et]:r}})}for(;i.length%q.length!==0;)i.push(Je());return i}function F(n){let e=W(n);return e?T(e):null}function L(n){let e=n?.metadata?.[Ze];return typeof e=="string"?e:null}function ee(n){let e=n?.metadata?.[et];return typeof e=="number"?e:null}function Yt(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function nt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:G.findIndex(t=>t.toLowerCase().startsWith(e))}function zt(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=r)return i;let o=new Date(t.getFullYear()+1,n,e);return o.getMonth()===n&&o.getDate()===e?o:null}function it(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function Q(n,e={}){if(!n)return null;let t=e.today??new Date,i=Yt(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=it(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?T(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=nt(o[1]);if(l>=0)return te(l,Number(o[2]),o[3],t)}let a=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(a){let l=nt(a[2]);if(l>=0)return te(l,Number(a[1]),a[3],t)}let s=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(s){let l=Number(s[1]),d=Number(s[2]);return l>12&&d<=12?te(d-1,l,s[3],t):d>12&&l<=12?te(l-1,d,s[3],t):null}return null}function te(n,e,t,i){if(t){if(t.length!==4)return null;let o=it(Number(t),n,e);return o?T(o):null}let r=zt(n,e,i);return r?T(r):null}function ne(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:Q(n.text,e)}var Xt=new Set(["date","dates"]),rt=3;function Jt(n){if(!n)return 0;let e=0;for(let t of n)if(t.is_tappable&&(Q(t.text)!==null&&(e+=1),e>=rt))return e;return e}function Zt(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function D(n){if(!n)return"options";let e=n.formatType;return e==="date"||e==="options"?e:Zt(n.type).some(t=>Xt.has(t))||Jt(n.options)>=rt?"date":"options"}var ie=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var en="https://api.ai-autocomplete.com",re=`${en}/api/suggest`,ot=new WeakMap;function j(n){return n?.type==="accessToken"}function tn(n){if(!(!n||j(n)))return n}function oe(n){let e=ot.get(n.getAccessToken);return e||(e=new ie(n),ot.set(n.getAccessToken,e)),e}function se(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function ae(n){let e=tn(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var $e="skipped";function H(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:$e,kind:null}));return i.length>0?[...n,...i]:n}var nn="0.14.0",st=!1;function rn(){return crypto.randomUUID()}function on(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function sn(n,e,t,i,r,o,a,s){let l=e.find(c=>c.type==="contact"&&c.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof l=="number"?l:void 0;return{data:{raw_query:n,completed_params:H(e.map(c=>on(c,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(c=>({type:c.type,value:c.text}))},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d},...s!==void 0&&{additional_context:s}},meta:{request_id:rn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:nn,session_id:i}}}async function at(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function lt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=sn(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),a=se(i),s=i?.endpoint??re,l=JSON.stringify(o);if(j(i)){let u=oe(i),p=await u.getToken(),h=await at(s,a,p,l,t.signal);if(h.status===401){let b=await u.getToken(!0);h=await at(s,a,b,l,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let d=ae(i);!d&&!st&&(st=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(a.Authorization=d);let c=await fetch(s,{method:"POST",headers:a,body:l,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function C(n,e){let t=n,i={},r=[],o=[],a=0;for(let s of e){let l=(i[s.type]??0)+1;i[s.type]=l;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=h=>{let b=t.indexOf(s.text,h);for(;b!==-1&&o.some(S=>b<S.end&&b+s.text.length>S.start);)b=t.indexOf(s.text,b+1);return b},p=u(a);if(p===-1&&(p=u(0)),p!==-1){t=t.slice(0,p)+c+t.slice(p+s.text.length);let h=c.length-s.text.length;for(let b of o)b.start>=p+s.text.length&&(b.start+=h,b.end+=h);o.push({start:p,end:p+c.length}),a=p>=a?p+c.length:a+h}r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function k(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 N(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function dt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let a=i.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return n.length-s}}return 0}function R(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function B(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function ct(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");return r?{...t,options:r}:t}):n}function ut(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function pt(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function mt(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function ft(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function Ke(n,e){let t=[],i=[],r=0;for(let o of e){let a=n.indexOf(o.text,r);if(a===-1){i.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:i}}function gt(n,e,t){let i=[],r=[],o=0;for(let a of t){let s=n.indexOf(a.text,o);for(;s!==-1&&e.some(l=>s<l.end&&s+a.text.length>l.start);)s=n.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}i.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:i,missing:r}}function ht(n,e,t=[]){let i=Ke(n,e).located,r=gt(n,i,t).located,o=[...i.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...r.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),a=[],s=0;for(let d of o)d.start>s&&a.push({type:"text",value:n.slice(s,d.start)}),a.push(d.segment),s=d.end;let l=n.slice(s);return l&&a.push({type:"text",value:l}),a}function bt(n,e){let{located:t,missing:i}=Ke(n,e);return{valid:t.map(r=>r.param),invalid:i}}function de(n,e,t){let i=Ke(n,e).located,{located:r,missing:o}=gt(n,i,t);return{valid:r.map(a=>a.param),invalid:o}}function an(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var ln=100,dn=300,cn=2,ce=class{constructor(e,t,i,r,o,a,s,l={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.getAdditionalContext=s;this.callbacks=l;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 r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?mt(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,l=await lt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let d=(l.data.input??[]).filter(g=>g.source==="identified").map(g=>({id:crypto.randomUUID(),type:g.type,text:g.text})),c=ct(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],p=u[u.length-1],h=this.store.get().text,b,S;if(p?.state==="in_progress"){S=!0;let g=h.toLowerCase().lastIndexOf(p.text.toLowerCase());b=g!==-1?g:o}else S=!1,b=o;let m=c.filter(g=>g.type!=="placeholder")[0],f=null;if(m&&D(m)!=="date"){let g=N(h,b,S),y=B(m.options,g);y&&(f={id:crypto.randomUUID(),placeholder:"",type:m.type,text:y.text,kind:y.kind,suggestionType:m.type,suggestionPlaceholder:m.text,options:m.options??[],metadata:y.metadata},c=c.filter(P=>P!==m),this.callbacks.onAutoMatch?.({active:m,matched:y,rawQuery:e}))}this.store.set(g=>{let y=f?[...g.completedParams,f]:g.completedParams,P=de(g.text,y,d).valid,v=new Set(a.skippedParams.map(w=>w.id)),I=new Set(g.skippedParams.filter(w=>!v.has(w.id)).map(w=>w.type));return{suggestions:I.size>0?c.filter(w=>w.type==="placeholder"||!I.has(w.type)):c,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:b,filterInProgress:S,identifiedParams:P,...f?{completedParams:y}:{}}})}catch(a){let s=an(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=k(r.text,r.filterBase,o),s=N(r.text,a,r.filterInProgress),d=r.suggestions.filter(g=>g.type!=="placeholder")[0],c=r.activeFormatType==="date",p=(d&&!c?R(d.options,s):[]).filter(g=>g.is_tappable),h=d&&!c?B(d.options,s)!==null:!1,b=s.trim().length>0;if(p.length>0&&!h&&b||le(r.text,r.completedParams.length,o))return!1;let{rawQuery:S,completedParams:x}=C(r.text,r.completedParams),m=S.length<r.lastRawQuery.length,f=Math.abs(S.length-r.lastRawQuery.length);return m||f>=i?(this.doFetch(S,x),!0):!1};this.debounceTimer=setTimeout(()=>{t(cn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ln),this.slowDebounceTimer=setTimeout(()=>t(1),dn)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var yt='[contenteditable="false"]',$;function un(){if($!==void 0)return $;let n=globalThis.Intl.Segmenter;if(!n)return $=null,null;try{$=new n(void 0,{granularity:"grapheme"})}catch{$=null}return $??null}function ue(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(yt))return!0;t=t.parentNode}return!1}function pe(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return ue(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Y(n){let e=pe(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function me(n){let e=pe(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function A(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(ue(r,n)&&r!==n)return null;let o=0;for(let a=0;a<i&&a<r.childNodes.length;a++)o+=St(r.childNodes[a],n);return o+xt(r,n)}return t.nodeType!==Node.TEXT_NODE||ue(t,n)?null:xt(t,n)+i}function St(n,e){if(n.nodeType===Node.TEXT_NODE)return ue(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(yt))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=St(r,e);return i}function xt(n,e){let t=pe(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function E(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,me(n))),o=pe(n),a=0,s=null,l=0,d=o.nextNode(),c=null;for(;d;){let p=d.data.length;if(r<a+p){s=d,l=r-a;break}if(r===a+p){let h=o.nextNode();h?(s=h,l=0):(s=d,l=p);break}a+=p,c=d,d=o.nextNode()}let u=t.createRange();if(s){let p=s.parentElement?.closest('strong[data-seg="completed"]');p&&p!==n&&n.contains(p)?l===0?u.setStartBefore(p):l===s.data.length?u.setStartAfter(p):u.setStart(s,l):u.setStart(s,l)}else c?u.setStart(c,c.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u)}function fe(n){let e=A(n);return e==null?!1:e>=me(n)}function ge(n,e){if(e<=0)return 0;let t=un();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function K(n,e,t=[]){let{rawQuery:i,completedParams:r}=C(n,e);return{query:n.trim(),raw_query:i,completed_params:H(r,t)}}function Ve(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")?fe(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Ue(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?A(n):null}var he=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let l=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=Ve(e.target,t),c=!!t.editingParam;if(!d&&!c&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(l)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!1):s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(s.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),s.length===0)return;if(t.activeFormatType==="date"){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===h){this.store.set({activeDropdownIndex:-1});break}}let u=s.indexOf(t.activeDropdownIndex),p=u<s.length-1?u+1:0;this.store.set({activeDropdownIndex:s[p]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!l)break;let u=Ve(e.target,t),p=!!t.editingParam;if(!u&&!p)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(s.length===0)return;this.store.set({activeDropdownIndex:h});break}if(s.length===0)break;if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let d=s.indexOf(t.activeDropdownIndex),c=d>0?d-1:s.length-1;this.store.set({activeDropdownIndex:s[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%o<o-1){let u=t.activeDropdownIndex+1;u<t.filteredOptions.length&&t.filteredOptions[u]?.is_tappable&&this.store.set({activeDropdownIndex:u})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),E(c,u);break}Ve(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%o>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=Ue(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,c=t.editingAnchor;this.ctx.exitEditMode?.(),E(d,c);break}if(this.ctx.startEditingParamAtCaret){let d=Ue(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Ue(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):a&&a(K(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((p,h)=>p.is_tappable?h:-1).filter(p=>p!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let p=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:p});break}e.preventDefault();let c=d.indexOf(t.activeDropdownIndex),u;if(c<0)u=e.shiftKey?d.length-1:0;else{let p=e.shiftKey?-1:1;u=(c+p+d.length)%d.length}this.store.set({activeDropdownIndex:d[u]});break}case"Escape":{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,c=t.editingTail;this.ctx.exitEditMode?.(),E(d,c)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}dateEntryIndex(e,t){let i=T(new Date),r=e.filteredOptions.findIndex(a=>L(a)===i);if(r>=0)return r;let o=e.filteredOptions.map((a,s)=>a.is_tappable?s:-1).filter(a=>a!==-1);return(t?o[o.length-1]:o[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((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var be=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.filter((d,c)=>c!==e),a=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=C(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let s=[...a,r,...o],l=this.store.peek({suggestions:s}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var xe=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,i){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(i);return}try{let o=await r.fetch(e,t);if(t.aborted||!i())return;let a=r.transform(o),s=Array.isArray(a)?a:[],l=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!i())return;this.commit(l)}catch(o){if(t.aborted||pn(o))return;this.logOnce(o),this.clear(i)}}}clearNow(){this.commit([])}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 pn(n){return n instanceof Error&&n.name==="AbortError"}var z="(max-width: 768px)";var mn="var(--aia-option-row-height, 37px)",fn="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ye(n,e){let t=(i,r)=>({cols:i,rows:r,maxHeight:`calc(${r} * ${mn} + ${fn})`});return e?t(1,Math.min(n,5)):n>=5&&n<=6?t(2,Math.ceil(n/2)):t(1,Math.min(n,4))}function Se(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function ve(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(z).matches}function vt(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,a=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let s=i?n.isFocused:!0;return a&&s}if(t==="auto"){let s=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,d=n.caretOffset==null||n.caretOffset>=l;return(a||n.isLoading)&&s&&d}return t==="manual"?(a||n.isLoading)&&n.pillTapped:!1}function Ge(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 gn(n){if(!n)return Be();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function hn(n){let e=W(n);return e?tt(e):Be()}function Pt(n,e){let t=ht(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(v=>v.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,a=n.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),s=k(n.text,Math.min(n.filterBase,n.text.length),a),d=s===0&&le(n.text,n.completedParams.length,a)?"":N(n.text,s,n.filterInProgress),c=r?o?o(d.trim())??r.options??[]:r.options??[]:[],u=n.editingParam!=null&&n.editingAnchor!=null,p;if(u&&n.editingParam&&n.editingAnchor!=null){let v=n.editingParam.id,I=n.completedParams.some(U=>U.id===v),_=n.caretOffset??n.editingAnchor,w=I?"":n.text.slice(n.editingAnchor,_);p=R(n.editingParam.options,w)}else p=R(c,d);let h=e.showNonTappableOptions===!1;h&&(p=p.filter(v=>v.is_tappable));let b=n.editingIdentified,S=b?{type:b.type}:u?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,x=D(S),m=null;if(x==="date"){let v=Ge({...n,actionableSuggestions:i}),I=n.dateViewMonth;m=I&&I.key===v?{year:I.year,month:I.month}:b?gn(b.iso):hn(n.editingParam?.text),p=Z(m)}let f=v=>h?v.is_tappable:!0,g;if(u){let v=n.editingParam?.options??[];g=n.editingParam!=null&&v.filter(f).length===0}else{let v=r?o?o("")??r.options??[]:r.options??[]:[];g=r!=null&&v.filter(f).length===0}let y=vt({inEditMode:u||b!=null,filteredOptionsLength:p.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:g,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),P=y&&n.activeDropdownIndex>=0&&!!p[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:p,activeFormatType:x,dateView:m,placeholderText:a,isDropdownOpen:y,isActivePillSelected:P}}function Pe(n){return n.mode==="fresh"?bn(n):xn(n)}function bn(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,s=i.filter(y=>y.type!=="placeholder")[0];if(!s?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),d=k(e,r,l),c=N(e,d,o),u=B(s.options,c);if(!u)return null;let p=u.text.toLowerCase(),h=e.toLowerCase().lastIndexOf(p),b=h>=0?h:Math.max(0,e.length-u.text.length),S=b+u.text.length,x=e.slice(b,S),f=S<e.length&&e[S]===" "?S+1:S,g={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:u.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:u.metadata};return{patch:{text:e,completedParams:[...t,g],suggestions:i.filter(y=>y!==s),filterBase:f,newParamId:g.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function xn(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(g=>g.id===i.id))return null;let a=e.slice(r,o),s=B(i.options,a);if(!s)return null;let l=s.text.toLowerCase(),d=a.toLowerCase().lastIndexOf(l),c=r+Math.max(0,d),u=c+s.text.length,p=e.slice(c,u),b=u<e.length&&e[u]===" "?u+1:u,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:p,kind:s.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:s.metadata},x=t.length,m=0;for(let g=0;g<t.length;g++){let y=e.indexOf(t[g].text,m);if(y!==-1){if(y>=b){x=g;break}m=y+t[g].text.length}}let f=[...t];return f.splice(x,0,S),{patch:{text:e,completedParams:f,newParamId:S.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}function we(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var Ce=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(a=>a.id===e);if(!i)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+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,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:a}=e===""?we(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(l=>({text:a,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!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.tryPromote()}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,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:C(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let a=t.text.slice(0,r),s=t.text.slice(o),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=s.length===0||s[0]!==" ",c=d?`${l} `:l,u=a+c+s,p=r+c.length+(d?0:1),h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},b=t.completedParams.findIndex(m=>m.id===i.id),S=t.completedParams.filter(m=>m.id!==i.id),x=b>=0?Math.min(b,S.length):S.length;S.splice(x,0,h),this.deps.store.set({text:u,completedParams:S,newParamId:h.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()}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Pe({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 qe="https://ai-autocomplete.com";function Ee(n=qe){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 Te(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var wt="data-aia-key";function M(n,e,t){let i=new Map;for(let a of Array.from(n.children)){let s=a.getAttribute(wt);s!=null&&i.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],l=t.keyOf(s,a);r.add(l);let d=i.get(l);d||(d=t.create(s,a),d.setAttribute(wt,l)),t.update?.(d,s,a),n.children[a]!==d&&n.insertBefore(d,n.children[a]??null),o.push(d)}for(let[a,s]of i)r.has(a)||s.remove();return o}function Et(n,e,t,i,r,o,a){let s=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){s?.remove();return}s||(s=vn(),n.appendChild(s));let l=s.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=X(r));let d=s.querySelector("[data-aia-date-prev]"),c=s.querySelector("[data-aia-date-next]");d&&(d.onclick=()=>a.onPreviousMonth()),c&&(c.onclick=()=>a.onNextMonth());let u=s.querySelector(".magicx-aia-datepicker-grid");u&&yn(u,e,t,i,o,a)}function yn(n,e,t,i,r,o){let a=T(new Date);M(n,e,{keyOf:(s,l)=>L(s)??`pad-${l}`,create:s=>Sn(s),update:(s,l,d)=>{let c=L(l),u=d===t&&l.is_tappable;s.id=`${i}-option-${d}`,s.dataset.aiaIndex=String(d),s.setAttribute("aria-selected",String(u)),s.classList.toggle("magicx-aia-date-cell--highlighted",u),s.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===a),s.classList.toggle("magicx-aia-date-cell--selected",c!=null&&r!=null&&c===r),l.is_tappable?(s.onclick=()=>{s.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(l),setTimeout(()=>s.classList.remove("magicx-aia-date-cell--pressed"),500)},s.onmouseenter=()=>{let p=Number.parseInt(s.dataset.aiaIndex??"-1",10);p>=0&&o.onHighlight(p)}):(s.onclick=null,s.onmouseenter=null)}})}function Sn(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=ee(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 vn(){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(Ct("prev","Previous month","\u2039"),t,Ct("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of q){let a=document.createElement("span");a.className="magicx-aia-datepicker-weekday",a.textContent=o,i.appendChild(a)}let r=document.createElement("div");return r.className="magicx-aia-datepicker-grid",r.setAttribute("data-aia-date-grid",""),n.append(e,i,r),n}function Ct(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",r=>r.preventDefault()),i}var Tt=[125,69];function It(n,e){return e?1:n===0?.7:n===1?.4:.2}function Ie(n,e,t,i,r=!1,o=!1,a=!1){let s=n.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",n.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let l=0;l<Tt.length;l++){let d=Tt[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(It(l,!1)),s.appendChild(c)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let l of s.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();M(s,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=l.text,d.addEventListener("mousedown",c=>c.preventDefault()),d},update:(l,d,c)=>{let u=l,p=a&&c===t&&!o,h=["magicx-aia-pill"];r&&h.push("magicx-aia-pill--rounded"),o&&h.push("magicx-aia-pill--skeleton"),u.className=h.join(" "),u.style.width="",u.style.opacity=String(It(c,p)),o?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(c))}})}function We(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Pn="Products";function At(n,e,t,i,r){let o=n.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=Pn;let l=document.createElement("div");l.className="magicx-aia-products-row",l.setAttribute("data-aia-products-row",""),o.append(s,l),n.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&M(a,e,{keyOf:s=>wn(s),create:s=>Cn(s,i,r),update:(s,l,d)=>{s.id=`${t}-product-${d}`,s.dataset.aiaIndex=String(d)}})}function Qe(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function wn(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Cn(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.href=n.url,i.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",n.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=n.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=n.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=n.title,o.appendChild(a),n.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=n.price,o.appendChild(s)}return i.appendChild(o),i.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(n))}),i.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}function En(n,e){let{cols:t,maxHeight:i}=ye(e,ve());n.style.gridTemplateColumns=Se(t),n.style.setProperty("--aia-grid-max-height",i)}function Ot(n,e,t,i,r,o,a,s=""){let l=n.querySelector(".aia-grid");if(e.length===0){l?.remove();return}l||(l=document.createElement("div"),l.className="aia-grid magicx-aia-grid",l.setAttribute("data-scroll",""),l.style.setProperty("--aia-grid-min","250px"),l.style.setProperty("--aia-grid-max","1fr"),l.style.setProperty("--aia-grid-gap","0"),n.appendChild(l)),En(l,e.length),In(l,e,t,i,r,o,a),Tn(l,s)}function Tn(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function In(n,e,t,i,r,o,a){let s=a?"1":"0";M(n,e,{keyOf:l=>`${l.text}\0${s}`,create:l=>An(l,a),update:(l,d,c)=>{let u=c===t&&!a;l.id=`${o}-option-${c}`,l.dataset.aiaIndex=String(c),l.setAttribute("aria-selected",String(u)),l.classList.toggle("magicx-aia-option--highlighted",u),!a&&d.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(d),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let p=Number.parseInt(l.dataset.aiaIndex??"-1",10);p>=0&&r(p)}):(l.onclick=null,l.onmouseenter=null)}})}function An(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=n.icon?`${n.icon} ${n.text}`:n.text,a.appendChild(s),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,a.appendChild(l)}return t.appendChild(a),t}var On=[159,119,164];function Ae(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}function Oe(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:p}=e,h=a.length>0,b=s&&h,S=t.length>0,x=e.products.length>0,m=r&&(S||b||o||x);if(m?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!m){Qe(n,!1);return}x?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let g=e.showSkipButton&&h&&!e.isInputEmpty,y=b||o&&s||g,P=f.querySelector(".magicx-aia-pill-bar");if(y){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),f.insertBefore(P,f.firstChild));let O=P.querySelector(".magicx-aia-pill-scroll");O||(O=document.createElement("span"),O.className="magicx-aia-pill-scroll",O.setAttribute("data-aia-pill-scroll",""),P.insertBefore(O,P.firstChild)),Ie(O,s?a:[],0,u,!0,o&&s,l),kn(P,g,o||e.skipDisabled,a[0],p)}else P&&P.remove();let v=e.suggestions[0],I=v?`${v.type} ${v.text}`:"",_=e.formatType==="date";Ot(f,_?[]:t,i,d,c,e.listboxId,o,I),Et(f,_?t:[],i,e.listboxId,_?e.dateView:null,e.selectedDateIso,{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let w=f.querySelector(".magicx-aia-skeleton-bars");if(o&&!S){if(!w){w=document.createElement("div"),w.className="magicx-aia-skeleton-bars",w.setAttribute("data-aia-skeleton-bars","");for(let O of On){let _e=document.createElement("span");_e.className="magicx-aia-skeleton-bar",_e.style.width=`${O}px`,w.appendChild(_e)}f.appendChild(w)}}else w&&w.remove();At(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Qe(n,!0);let U=f.querySelector(".magicx-aia-footer")??Ln(),Vt=i>=0&&!!t[i]?.is_tappable;Mn(U,Te(Vt,e.isInputEmpty)),U.isConnected||f.appendChild(U),Dn(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Dn(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 kn(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",a=>a.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Mn(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function Ln(){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 r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=Ee(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),n.append(e),n}function Dt(n,e){let t=Ae(e.listboxId);return n.appendChild(t),{dropdown:t}}function je(n,e,t){Oe(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text: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,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:e.editingIdentified?e.editingIdentified.iso:F(e.editingParam?.text),onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Nn=6,Rn=.3;function kt(n){return n<=0?"0px":`${(-Math.min(Rn,2*Nn/n)).toFixed(3)}px`}function De(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:a}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let l=t.map(x=>`${x.type}:${x.value}`).join("\0"),d=e.dataset.segKey??"",c=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(l===d&&(i??"")===c&&(r??"")===u)return;let p=a?A(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=e.ownerDocument??document,b=h.createDocumentFragment(),S=0;for(let x of t)if(S+=x.value.length,x.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=x.param.id;let f=x.param.id===i,g=x.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];f&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),g&&y.push("magicx-aia-segment--editing"),m.className=y.join(" "),m.style.letterSpacing=kt(x.value.length),m.textContent=x.value,b.appendChild(m)}else if(x.type==="identified"){let m=h.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=x.param.id;let f=["magicx-aia-segment","magicx-aia-segment--completed"];x.param.id===r&&f.push("magicx-aia-segment--editing"),m.className=f.join(" "),m.style.letterSpacing=kt(x.value.length),m.textContent=x.value,b.appendChild(m)}else b.appendChild(h.createTextNode(x.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(S),p!=null&&E(e,Math.max(0,Math.min(p,S)))}var _n='<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 Mt(){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=_n,n}function Fn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Lt(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Nt(n,e){let{listboxId:t}=e,i=Ae(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Fn()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let l=null,d=null;e.submitButton===void 0?(l=Mt(),r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d));let c=new AbortController,{signal:u}=c,p=!1,h=0,b=()=>{let m=Y(a),g=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(g)},S=()=>{let m=(a.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let f=m.anchorNode;return!f||!a.contains(f)?null:(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||a.focus()},{signal:u}),a.addEventListener("input",()=>{p||(h=performance.now(),b(),e.handleCaretAfterInput(A(a)))},{signal:u});let x=a.ownerDocument??document;if(x.addEventListener("selectionchange",()=>{let m=x.getSelection();if(!m||m.rangeCount===0||!a.contains(m.anchorNode))return;let f=m.isCollapsed?S():null,g=e.store.get(),y=g.editingParam?.id??g.editingIdentified?.id??null;if(f&&f!==y){e.startEditingParam(f);return}performance.now()-h<50||e.handleCaretMove(A(a))},{signal:u}),a.addEventListener("compositionstart",()=>{p=!0},{signal:u}),a.addEventListener("compositionend",()=>{p=!1,b()},{signal:u}),a.addEventListener("beforeinput",m=>{let f=m,g=f.inputType;if(g==="insertParagraph"||g==="insertLineBreak"||g==="insertFromDrop"){m.preventDefault();return}if(g.startsWith("insert")||g.startsWith("delete")){let y=g.startsWith("delete")?"":f.data??"";e.replaceEditingRange(y)&&m.preventDefault()}},{signal:u}),a.addEventListener("paste",m=>{m.preventDefault();let f=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let g=a.ownerDocument??document,y=g.getSelection();if(!y||y.rangeCount===0)return;let P=y.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let v=g.createTextNode(f);P.insertNode(v),P.setStartAfter(v),P.collapse(!0),y.removeAllRanges(),y.addRange(P),b()},{signal:u}),a.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:u}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",m=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation(),e.onSubmit(K(f.text,f.completedParams,f.skippedParams))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){a.focus();let m=a.ownerDocument??document,f=m.getSelection(),g=f&&f.rangeCount>0&&a.contains(f.anchorNode);if(f&&!g){let y=m.createRange();y.selectNodeContents(a),y.collapse(!0),f.removeAllRanges(),f.addRange(y)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Lt(a,s));m.observe(a),c.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:i,submitButton:l,abort:c}}function Ye(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:a}=n,{pillPlacement:s,setActivePill:l,selectOption:d,store:c}=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"),a){let x=!!e.text||e.completedParams.length>0;a.disabled=!x}let p=i.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==p;if(De({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let x=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;x||e.actionableSuggestions.length>0?Ie(r,e.actionableSuggestions,0,l,!1,x,e.isActivePillSelected):We(r)}else We(r);Lt(i,r),h?(i.focus(),E(i,e.caretOffset??e.text.length)):e.isFocused&&Y(i)!==e.text&&E(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:e.editingIdentified.type,required:!0,options:[]}:null,S=b??e.actionableSuggestions[0];Oe(o,{suggestions:S?[{...S,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:b?[b]:e.actionableSuggestions,showPills:s==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:e.editingIdentified?e.editingIdentified.iso:F(e.editingParam?.text),onSelect:d,onHighlight:x=>c.set({activeDropdownIndex:x}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:x=>c.set({isFocused:x})})}function Rt(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,a=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||a)&&n.placeholderText&&(r=`${n.placeholderText} `);let s=dt(r,e.text);s>0&&(r=r.slice(0,r.length-s));let l=r.length>0&&r[r.length-1]!==" ",d=`${r}${l?" ":""}${e.text} `,c=(o||a)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=u>=0?c.slice(u,u+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:t.type,text:p,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},b=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,h],newParamId:h.id,caretOffset:c.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:b}}function ke(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},i.push([e,s]),!r){r=!0;try{let l=0;for(let d=i.shift();d;d=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[c,u]=d;for(let p of t)p(c,u)}}catch(l){throw i.length=0,l}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function _t(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(a=>{let s={...a,...r(a)};return o(s)}):n.set(o)},peek:o=>{let a={...n.get(),...o};return{...a,...e(a)}},subscribe:o=>n.subscribe((a,s)=>{let l={...s,...r(s)},d={...a,...r(a)};o(d,l)})}}var ze=!1;function Ft(){if(ze||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){ze=!0;return}ze=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Hn,document.head.appendChild(n)}var Hn=`@layer layout {
1
+ "use strict";var je=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var Dn=Object.getOwnPropertyNames;var Ln=Object.prototype.hasOwnProperty;var kn=(n,e)=>{for(var t in e)je(n,t,{get:e[t],enumerable:!0})},Rn=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Dn(e))!Ln.call(n,r)&&r!==t&&je(n,r,{get:()=>e[r],enumerable:!(i=Mn(e,r))||i.enumerable});return n};var _n=n=>Rn(je({},"__esModule",{value:!0}),n);var Wi={};kn(Wi,{AIAutocomplete:()=>Qe,ATTRIBUTION_URL:()=>lt,ModeController:()=>q,OPTIONS_GRID_MOBILE_QUERY:()=>Z,OPTION_ENTER_DELAY_VAR:()=>Re,OPTION_ENTER_FADE_MS:()=>un,OPTION_ENTER_RISE_MS:()=>pn,OPTION_ENTER_RISE_PX:()=>mn,OPTION_ENTER_STAGGER_MS:()=>cn,PLACEHOLDER_FADE_OUT_MS:()=>Xt,PLACEHOLDER_LEAVING_ATTR:()=>H,PLACEHOLDER_SWAP_GAP_MS:()=>Jt,PLACEHOLDER_TYPE_MS:()=>jt,PLACEHOLDER_WORD_PAUSE_MS:()=>zt,SCROLL_ARROW_ATTR:()=>pt,SCROLL_ARROW_BOTTOM_VAR:()=>mt,SCROLL_ARROW_CLASS:()=>ut,SCROLL_ARROW_LABEL:()=>ft,SCROLL_ARROW_VISIBLE_ATTR:()=>He,SKIPPED_PARAM_TEXT:()=>et,WEEKDAY_LABELS:()=>Y,addMonths:()=>te,attachScrollArrow:()=>Fe,buildAttributionUrl:()=>De,buildDateOptions:()=>ne,buildQuery:()=>E,buildSubmitResult:()=>K,cellDay:()=>ie,cellIso:()=>R,computeOptionsGridLayout:()=>ot,createStore:()=>We,cursorIsAtEnd:()=>xe,extractPlainText:()=>J,formatDate:()=>Je,getCursorOffset:()=>I,getFooterHint:()=>Le,identifiedParamLabel:()=>M,isOptionsGridMobileViewport:()=>Ce,isoDate:()=>C,measureOptionsGrid:()=>Te,monthLabel:()=>ee,needsOptionsGridMeasurement:()=>we,optionEnterDelayMs:()=>_e,optionsEntranceDurationMs:()=>Ne,optionsGridTemplateColumns:()=>st,parseDate:()=>j,parseLooseDate:()=>z,plainTextLength:()=>be,planOptionsGrid:()=>Ee,previousGraphemeBoundary:()=>ye,renderEditableContent:()=>$e,resolveFormatType:()=>D,resolveIdentifiedDate:()=>oe,scrollCaretIntoView:()=>fe,selectedIsoFromText:()=>G,setCursorOffset:()=>T,withSkippedParams:()=>V});module.exports=_n(Wi);function ze(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function M(n){let e=ze(n);return e.length>0?e.join(" "):n}var B=["January","February","March","April","May","June","July","August","September","October","November","December"],Y=["S","M","T","W","T","F","S"],vt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Pt="aiaDate",wt="aiaDay",yt=n=>String(n).padStart(2,"0");function C(n){return`${n.getFullYear()}-${yt(n.getMonth()+1)}-${yt(n.getDate())}`}function Xe(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Nn(n){let e=Xe(n).getTime()-Xe(new Date).getTime();return Math.round(e/864e5)}function Je(n){let e=Nn(n);return e>=0&&e<7?vt[n.getDay()]:n.getFullYear()===new Date().getFullYear()?`${B[n.getMonth()]} ${n.getDate()}`:`${B[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function j(n){if(!n)return null;let e=vt.findIndex(s=>s.toLowerCase()===n.trim().toLowerCase());if(e>=0){let s=Xe(new Date),d=(e-s.getDay()+7)%7;return new Date(s.getFullYear(),s.getMonth(),s.getDate()+d)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=B.findIndex(s=>s.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let r=Number(t[2]),o=t[3]?Number(t[3]):new Date().getFullYear(),a=new Date(o,i,r);return a.getMonth()!==i||a.getDate()!==r?null:a}function ee(n){return`${B[n.month]} ${n.year}`}function Ze(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Et(n){return{year:n.getFullYear(),month:n.getMonth()}}function te(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function St(){return{text:"",is_tappable:!1,kind:null}}function ne(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let r=0;r<e;r++)i.push(St());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Je(o),is_tappable:!0,kind:null,metadata:{[Pt]:C(o),[wt]:r}})}for(;i.length%Y.length!==0;)i.push(St());return i}function G(n){let e=j(n);return e?C(e):null}function R(n){let e=n?.metadata?.[Pt];return typeof e=="string"?e:null}function ie(n){let e=n?.metadata?.[wt];return typeof e=="number"?e:null}function Hn(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Tt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:B.findIndex(t=>t.toLowerCase().startsWith(e))}function Fn(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=r)return i;let o=new Date(t.getFullYear()+1,n,e);return o.getMonth()===n&&o.getDate()===e?o:null}function Ct(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function z(n,e={}){if(!n)return null;let t=e.today??new Date,i=Hn(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let d=Ct(Number(r[1]),Number(r[2])-1,Number(r[3]));return d?C(d):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let d=Tt(o[1]);if(d>=0)return re(d,Number(o[2]),o[3],t)}let a=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(a){let d=Tt(a[2]);if(d>=0)return re(d,Number(a[1]),a[3],t)}let s=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(s){let d=Number(s[1]),l=Number(s[2]);return d>12&&l<=12?re(l-1,d,s[3],t):l>12&&d<=12?re(d-1,l,s[3],t):null}return null}function re(n,e,t,i){if(t){if(t.length!==4)return null;let o=Ct(Number(t),n,e);return o?C(o):null}let r=Fn(n,e,i);return r?C(r):null}function oe(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:z(n.text,e)}var Bn=new Set(["date","dates"]),At=3;function Gn(n){if(!n)return 0;let e=0;for(let t of n)if(t.is_tappable&&(z(t.text)!==null&&(e+=1),e>=At))return e;return e}function D(n){if(!n)return"options";let e=n.formatType;return e==="date"||e==="options"?e:ze(n.type).some(t=>Bn.has(t))||Gn(n.options)>=At?"date":"options"}var se=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 Vn="https://api.ai-autocomplete.com",ae=`${Vn}/api/suggest`,It=new WeakMap;function X(n){return n?.type==="accessToken"}function $n(n){if(!(!n||X(n)))return n}function le(n){let e=It.get(n.getAccessToken);return e||(e=new se(n),It.set(n.getAccessToken,e)),e}function de(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function ce(n){let e=$n(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var et="skipped";function V(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:et,kind:null}));return i.length>0?[...n,...i]:n}var Wn="0.15.0",Ot=!1;function Kn(){return crypto.randomUUID()}function Un(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function qn(n,e,t,i,r,o,a,s){let d=e.find(c=>c.type==="contact"&&c.metadata?.contact_account_count)?.metadata?.contact_account_count,l=typeof d=="number"?d:void 0;return{data:{raw_query:n,completed_params:V(e.map(c=>Un(c,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(c=>({type:c.type,value:c.text}))},...o&&o.length>0&&{recently_suggested:o},...l!=null&&{contact_account_count:l},...s!==void 0&&{additional_context:s}},meta:{request_id:Kn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Wn,session_id:i}}}async function Mt(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Dt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=qn(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),a=de(i),s=i?.endpoint??ae,d=JSON.stringify(o);if(X(i)){let u=le(i),p=await u.getToken(),g=await Mt(s,a,p,d,t.signal);if(g.status===401){let b=await u.getToken(!0);g=await Mt(s,a,b,d,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=ce(i);!l&&!Ot&&(Ot=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(a.Authorization=l);let c=await fetch(s,{method:"POST",headers:a,body:d,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function E(n,e){let t=n,i={},r=[],o=[],a=0;for(let s of e){let d=(i[s.type]??0)+1;i[s.type]=d;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,u=g=>{let b=t.indexOf(s.text,g);for(;b!==-1&&o.some(y=>b<y.end&&b+s.text.length>y.start);)b=t.indexOf(s.text,b+1);return b},p=u(a);if(p===-1&&(p=u(0)),p!==-1){t=t.slice(0,p)+c+t.slice(p+s.text.length);let g=c.length-s.text.length;for(let b of o)b.start>=p+s.text.length&&(b.start+=g,b.end+=g);o.push({start:p,end:p+c.length}),a=p>=a?p+c.length:a+g}r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function L(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function ue(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function _(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Lt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let a=i.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return n.length-s}}return 0}function N(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function $(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function kt(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");return r?{...t,options:r}:t}):n}function Rt(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function _t(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function Nt(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function Ht(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function tt(n,e){let t=[],i=[],r=0;for(let o of e){let a=n.indexOf(o.text,r);if(a===-1){i.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:i}}function Ft(n,e,t){let i=[],r=[],o=0;for(let a of t){let s=n.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=n.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}i.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:i,missing:r}}function Bt(n,e,t=[]){let i=tt(n,e).located,r=Ft(n,i,t).located,o=[...i.map(l=>({start:l.start,end:l.end,segment:{type:"completed",value:l.param.text,param:l.param}})),...r.map(l=>({start:l.start,end:l.end,segment:{type:"identified",value:l.param.text,param:l.param}}))].sort((l,c)=>l.start-c.start),a=[],s=0;for(let l of o)l.start>s&&a.push({type:"text",value:n.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=n.slice(s);return d&&a.push({type:"text",value:d}),a}function Gt(n,e){let{located:t,missing:i}=tt(n,e);return{valid:t.map(r=>r.param),invalid:i}}function pe(n,e,t){let i=tt(n,e).located,{located:r,missing:o}=Ft(n,i,t);return{valid:r.map(a=>a.param),invalid:o}}function Qn(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Yn=100,jn=300,zn=2,me=class{constructor(e,t,i,r,o,a,s,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.getAdditionalContext=s;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,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 r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?Nt(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await Dt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(h=>h.source==="identified").map(h=>({id:crypto.randomUUID(),type:h.type,text:h.text})),c=kt(d.data.suggestions??[],this.getOptionOverrides()),u=d.data.input??[],p=u[u.length-1],g=this.store.get().text,b,y;if(p?.state==="in_progress"){y=!0;let h=g.toLowerCase().lastIndexOf(p.text.toLowerCase());b=h!==-1?h:o}else y=!1,b=o;let m=c.filter(h=>h.type!=="placeholder")[0],f=null;if(m&&D(m)!=="date"){let h=_(g,b,y),S=$(m.options,h);S&&(f={id:crypto.randomUUID(),placeholder:"",type:m.type,text:S.text,kind:S.kind,suggestionType:m.type,suggestionPlaceholder:m.text,options:m.options??[],metadata:S.metadata},c=c.filter(P=>P!==m),this.callbacks.onAutoMatch?.({active:m,matched:S,rawQuery:e}))}this.store.set(h=>{let S=f?[...h.completedParams,f]:h.completedParams,P=pe(h.text,S,l).valid,v=new Set(a.skippedParams.map(w=>w.id)),A=new Set(h.skippedParams.filter(w=>!v.has(w.id)).map(w=>w.type));return{suggestions:A.size>0?c.filter(w=>w.type==="placeholder"||!A.has(w.type)):c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:b,filterInProgress:y,identifiedParams:P,...f?{completedParams:S}:{}}})}catch(a){let s=Qn(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" "),a=L(r.text,r.filterBase,o),s=_(r.text,a,r.filterInProgress),l=r.suggestions.filter(h=>h.type!=="placeholder")[0],c=r.activeFormatType==="date",p=(l&&!c?N(l.options,s):[]).filter(h=>h.is_tappable),g=l&&!c?$(l.options,s)!==null:!1,b=s.trim().length>0;if(p.length>0&&!g&&b||ue(r.text,r.completedParams.length,o))return!1;let{rawQuery:y,completedParams:x}=E(r.text,r.completedParams),m=y.length<r.lastRawQuery.length,f=Math.abs(y.length-r.lastRawQuery.length);return m||f>=i?(this.doFetch(y,x),!0):!1};this.debounceTimer=setTimeout(()=>{t(zn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Yn),this.slowDebounceTimer=setTimeout(()=>t(1),jn)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Xn="magicx-aia";function Vt(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Jn(n){let e=n.ownerDocument??document,t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let r=i.scrollWidth>i.clientWidth,o=i.scrollHeight>i.clientHeight;if(r||o){let a=t.getComputedStyle(i);if(r&&Vt(a.overflowX)||o&&Vt(a.overflowY))return i}if(i.classList.contains(Xn))return null;i=i.parentElement}return null}function fe(n){let t=(n.ownerDocument??document).getSelection();if(!t||t.rangeCount===0)return;let i=t.getRangeAt(0);if(!i.collapsed||!n.contains(i.startContainer))return;let r=Jn(n);if(!r||typeof i.getBoundingClientRect!="function")return;let o=i.getBoundingClientRect();if(o.height===0)return;let a=r.getBoundingClientRect();if(r.scrollWidth>r.clientWidth){let s=a.left+r.clientLeft,d=s+r.clientWidth;o.right>d?r.scrollLeft+=o.right-d+2:o.left<s&&(r.scrollLeft-=s-o.left+2)}if(r.scrollHeight>r.clientHeight){let s=a.top+r.clientTop,d=s+r.clientHeight;o.bottom>d?r.scrollTop+=o.bottom-d+2:o.top<s&&(r.scrollTop-=s-o.top+2)}}var Wt='[contenteditable="false"]',W;function Zn(){if(W!==void 0)return W;let n=globalThis.Intl.Segmenter;if(!n)return W=null,null;try{W=new n(void 0,{granularity:"grapheme"})}catch{W=null}return W??null}function ge(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Wt))return!0;t=t.parentNode}return!1}function he(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return ge(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function J(n){let e=he(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function be(n){let e=he(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function I(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(ge(r,n)&&r!==n)return null;let o=0;for(let a=0;a<i&&a<r.childNodes.length;a++)o+=Kt(r.childNodes[a],n);return o+$t(r,n)}return t.nodeType!==Node.TEXT_NODE||ge(t,n)?null:$t(t,n)+i}function Kt(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(Wt))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=Kt(r,e);return i}function $t(n,e){let t=he(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function T(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,be(n))),o=he(n),a=0,s=null,d=0,l=o.nextNode(),c=null;for(;l;){let p=l.data.length;if(r<a+p){s=l,d=r-a;break}if(r===a+p){let g=o.nextNode();g?(s=g,d=0):(s=l,d=p);break}a+=p,c=l,l=o.nextNode()}let u=t.createRange();if(s){let p=s.parentElement?.closest('strong[data-seg="completed"]');p&&p!==n&&n.contains(p)?d===0?u.setStartBefore(p):d===s.data.length?u.setStartAfter(p):u.setStart(s,d):u.setStart(s,d)}else c?u.setStart(c,c.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u),fe(n)}function xe(n){let e=I(n);return e==null?!1:e>=be(n)}function ye(n,e){if(e<=0)return 0;let t=Zn();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function K(n,e,t=[]){let{rawQuery:i,completedParams:r}=E(n,e);return{query:n.trim(),raw_query:i,completed_params:V(r,t)}}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")?xe(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function it(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?I(n):null}var Se=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=nt(e.target,t),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;e.preventDefault();let g=t.activeFormatType==="date"?this.dateEntryIndex(t,!1):s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:g});break}if(s.length===0)return;this.store.set({activeDropdownIndex:g});break}if(e.preventDefault(),s.length===0)return;if(t.activeFormatType==="date"){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let g=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===g){this.store.set({activeDropdownIndex:-1});break}}let u=s.indexOf(t.activeDropdownIndex),p=u<s.length-1?u+1:0;this.store.set({activeDropdownIndex:s[p]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let u=nt(e.target,t),p=!!t.editingParam;if(!u&&!p)break;e.preventDefault();let g=t.activeFormatType==="date"?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:g});break}if(s.length===0)return;this.store.set({activeDropdownIndex:g});break}if(s.length===0)break;if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let l=s.indexOf(t.activeDropdownIndex),c=l>0?l-1:s.length-1;this.store.set({activeDropdownIndex:s[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%o<o-1){let u=t.activeDropdownIndex+1;u<t.filteredOptions.length&&t.filteredOptions[u]?.is_tappable&&this.store.set({activeDropdownIndex:u})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),T(c,u);break}nt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%o>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let l=it(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),T(l,c);break}if(this.ctx.startEditingParamAtCaret){let l=it(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=it(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i):a&&a(K(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let l=t.filteredOptions.map((p,g)=>p.is_tappable?g:-1).filter(p=>p!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let p=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:p});break}e.preventDefault();let c=l.indexOf(t.activeDropdownIndex),u;if(c<0)u=e.shiftKey?l.length-1:0;else{let p=e.shiftKey?-1:1;u=(c+p+l.length)%l.length}this.store.set({activeDropdownIndex:l[u]});break}case"Escape":{if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),T(l,c)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}dateEntryIndex(e,t){let i=C(new Date),r=e.filteredOptions.findIndex(a=>R(a)===i);if(r>=0)return r;let o=e.filteredOptions.map((a,s)=>a.is_tappable?s:-1).filter(a=>a!==-1);return(t?o[o.length-1]:o[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((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var ve=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.filter((l,c)=>c!==e),a=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=E(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let s=[...a,r,...o],d=this.store.peek({suggestions:s}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Pe=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,i){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(i);return}try{let o=await r.fetch(e,t);if(t.aborted||!i())return;let a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!i())return;this.commit(d)}catch(o){if(t.aborted||ei(o))return;this.logOnce(o),this.clear(i)}}}clearNow(){this.commit([])}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 ei(n){return n instanceof Error&&n.name==="AbortError"}var Z="(max-width: 768px)";var ti="var(--aia-option-row-height, 37px)",ni="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ot(n,e){return e?rt(1,Math.min(n,5)):rt(1,Math.min(n,4))}function rt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${ti} + ${ni})`}}function we(n,e){return!e&&n>=5}function Ee(n,e,t,i){if(!(!e&&n>=5&&ii(t,i))){let d=ot(n,e);return{...d,template:st(d.cols),scrollHintIndices:!e&&n>d.rows?[d.rows-1]:[]}}let[o,a]=Ut(t),s=6;return{...rt(2,3),template:`minmax(0,${o}fr) minmax(0,${a}fr)`,scrollHintIndices:n>s?[s-2,s-1]:[]}}function Ut(n){let e=0,t=0;return n.forEach((i,r)=>{r%2===0?e=Math.max(e,i):t=Math.max(t,i)}),[Math.ceil(e),Math.ceil(t)]}function ii(n,e){if(!n||n.length===0||e==null||e<=0||n.some(r=>r<=0))return!1;let[t,i]=Ut(n);return t+i<=e}function Te(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 a of e){let s=a.cloneNode(!0);s.removeAttribute("id"),s.removeAttribute("role"),s.removeAttribute("aria-selected"),s.style.whiteSpace="nowrap",s.style.width="max-content",t.appendChild(s)}n.appendChild(t);let i=Array.from(t.children).map(a=>a.offsetWidth);t.remove();let r=getComputedStyle(n),o=n.clientWidth-(Number.parseFloat(r.paddingLeft)||0)-(Number.parseFloat(r.paddingRight)||0)-(Number.parseFloat(r.columnGap)||0);return{rowWidths:i,gridWidth:o}}function st(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Ce(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Z).matches}function qt(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,a=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let s=i?n.isFocused:!0;return a&&s}if(t==="auto"){let s=i?n.isFocused:!0,d=n.text.replace(/\s+$/,"").length,l=n.caretOffset==null||n.caretOffset>=d;return(a||n.isLoading)&&s&&l}return t==="manual"?(a||n.isLoading)&&n.pillTapped:!1}function at(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 ri(n){if(!n)return Ze();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function oi(n){let e=j(n);return e?Et(e):Ze()}function Qt(n,e){let t=Bt(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(v=>v.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,a=n.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),s=L(n.text,Math.min(n.filterBase,n.text.length),a),l=s===0&&ue(n.text,n.completedParams.length,a)?"":_(n.text,s,n.filterInProgress),c=r?o?o(l.trim())??r.options??[]:r.options??[]:[],u=n.editingParam!=null&&n.editingAnchor!=null,p;if(u&&n.editingParam&&n.editingAnchor!=null){let v=n.editingParam.id,A=n.completedParams.some(Q=>Q.id===v),F=n.caretOffset??n.editingAnchor,w=A?"":n.text.slice(n.editingAnchor,F);p=N(n.editingParam.options,w)}else p=N(c,l);let g=e.showNonTappableOptions===!1;g&&(p=p.filter(v=>v.is_tappable));let b=n.editingIdentified,y=b?{type:b.type}:u?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,x=D(y),m=null;if(x==="date"){let v=at({...n,actionableSuggestions:i}),A=n.dateViewMonth;m=A&&A.key===v?{year:A.year,month:A.month}:b?ri(b.iso):oi(n.editingParam?.text),p=ne(m)}let f=v=>g?v.is_tappable:!0,h;if(u){let v=n.editingParam?.options??[];h=n.editingParam!=null&&v.filter(f).length===0}else{let v=r?o?o("")??r.options??[]:r.options??[]:[];h=r!=null&&v.filter(f).length===0}let S=qt({inEditMode:u||b!=null,filteredOptionsLength:p.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:h,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),P=S&&n.activeDropdownIndex>=0&&!!p[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:p,activeFormatType:x,dateView:m,placeholderText:a,isDropdownOpen:S,isActivePillSelected:P}}function Ae(n){return n.mode==="fresh"?si(n):ai(n)}function si(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,s=i.filter(S=>S.type!=="placeholder")[0];if(!s?.options)return null;let d=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=L(e,r,d),c=_(e,l,o),u=$(s.options,c);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,x=e.slice(b,y),f=y<e.length&&e[y]===" "?y+1:y,h={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:u.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:u.metadata};return{patch:{text:e,completedParams:[...t,h],suggestions:i.filter(S=>S!==s),filterBase:f,newParamId:h.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function ai(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(h=>h.id===i.id))return null;let a=e.slice(r,o),s=$(i.options,a);if(!s)return null;let d=s.text.toLowerCase(),l=a.toLowerCase().lastIndexOf(d),c=r+Math.max(0,l),u=c+s.text.length,p=e.slice(c,u),g=u<e.length&&e[u]===" "?u+1:u,b=e.length,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:p,kind:s.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:s.metadata},x=t.length,m=0;for(let h=0;h<t.length;h++){let S=e.indexOf(t[h].text,m);if(S!==-1){if(S>=g){x=h;break}m=S+t[h].text.length}}let f=[...t];return f.splice(x,0,y),{patch:{text:e,completedParams:f,newParamId:y.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}function Ie(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var Oe=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(a=>a.id===e);if(!i)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+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,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(d=>d.id===i.id))return!1;let{text:a}=e===""?Ie(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(d=>({text:a,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!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.tryPromote()}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,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:E(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let a=t.text.slice(0,r),s=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=s.length===0||s[0]!==" "?`${d} `:d,u=a+c+s,p=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:d,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},b=t.completedParams.findIndex(m=>m.id===i.id),y=t.completedParams.filter(m=>m.id!==i.id),x=b>=0?Math.min(b,y.length):y.length;y.splice(x,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()}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Ae({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 jt=33,zt=70,Xt=120,Jt=50,H="data-aia-placeholder-leaving",U=new WeakMap;function Me(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function li(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Zt(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function en(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Zt(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(()=>en(n,e),33+i)}function Yt(n,e){Zt(n,e,0),e.timer=setTimeout(()=>en(n,e),33)}function tn(n,e){let t=U.get(n);if(e===""){t&&(Me(t),U.delete(n)),n.removeAttribute(H),delete n.dataset.placeholder;return}if(t?.target===e)return;if(li(n)){t&&Me(t),n.removeAttribute(H),U.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},r=t&&t.shown>0?t:null;if(t&&Me(t),U.set(n,i),r){n.setAttribute(H,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(H),n.isConnected&&Yt(n,i)},170);return}n.removeAttribute(H),Yt(n,i)}function nn(n){let e=U.get(n);e&&(Me(e),U.delete(n))}var lt="https://ai-autocomplete.com";function De(n=lt){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 Le(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var rn="data-aia-key";function k(n,e,t){let i=new Map;for(let a of Array.from(n.children)){let s=a.getAttribute(rn);s!=null&&i.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],d=t.keyOf(s,a);r.add(d);let l=i.get(d);l||(l=t.create(s,a),l.setAttribute(rn,d)),t.update?.(l,s,a),n.children[a]!==l&&n.insertBefore(l,n.children[a]??null),o.push(l)}for(let[a,s]of i)r.has(a)||s.remove();return o}function sn(n,e,t,i,r,o,a){let s=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){s?.remove();return}s||(s=ui(),n.appendChild(s));let d=s.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=ee(r));let l=s.querySelector("[data-aia-date-prev]"),c=s.querySelector("[data-aia-date-next]");l&&(l.onclick=()=>a.onPreviousMonth()),c&&(c.onclick=()=>a.onNextMonth());let u=s.querySelector(".magicx-aia-datepicker-grid");u&&di(u,e,t,i,o,a)}function di(n,e,t,i,r,o){let a=C(new Date);k(n,e,{keyOf:(s,d)=>R(s)??`pad-${d}`,create:s=>ci(s),update:(s,d,l)=>{let c=R(d),u=l===t&&d.is_tappable;s.id=`${i}-option-${l}`,s.dataset.aiaIndex=String(l),s.setAttribute("aria-selected",String(u)),s.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<a),s.classList.toggle("magicx-aia-date-cell--highlighted",u),s.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===a),s.classList.toggle("magicx-aia-date-cell--selected",c!=null&&r!=null&&c===r),d.is_tappable?(s.onclick=()=>{s.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(d),setTimeout(()=>s.classList.remove("magicx-aia-date-cell--pressed"),500)},s.onmouseenter=()=>{let p=Number.parseInt(s.dataset.aiaIndex??"-1",10);p>=0&&o.onHighlight(p)}):(s.onclick=null,s.onmouseenter=null)}})}function ci(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=ie(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 ui(){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(on("prev","Previous month","\u2039"),t,on("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of Y){let a=document.createElement("span");a.className="magicx-aia-datepicker-weekday",a.textContent=o,i.appendChild(a)}let r=document.createElement("div");return r.className="magicx-aia-datepicker-grid",r.setAttribute("data-aia-date-grid",""),n.append(e,i,r),n}function on(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",r=>r.preventDefault()),i}var an=[125,69];function ln(n,e){return e?1:n===0?.7:n===1?.4:.2}function ke(n,e,t,i,r=!1,o=!1,a=!1){let s=n.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",n.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<an.length;d++){let l=an[d],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(ln(d,!1)),s.appendChild(c)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let d of s.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();k(s,e,{keyOf:d=>`${d.type}-${d.text}`,create:d=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=d.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(d,l,c)=>{let u=d,p=a&&c===t&&!o,g=["magicx-aia-pill"];r&&g.push("magicx-aia-pill--rounded"),o&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(ln(c,p)),o?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(c))}})}function dt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var pi="Products";function dn(n,e,t,i,r){let o=n.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=pi;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),n.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&k(a,e,{keyOf:s=>mi(s),create:s=>fi(s,i,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function ct(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function mi(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function fi(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.href=n.url,i.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",n.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=n.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=n.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=n.title,o.appendChild(a),n.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=n.price,o.appendChild(s)}return i.appendChild(o),i.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(n))}),i.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var cn=80,un=150,pn=280,mn=16,Re="--aia-option-enter-delay";function _e(n,e,t,i="below"){let r=Math.max(1,Math.floor(e)),o=Math.floor(Math.max(0,n)/r);if(i!=="above")return o*80;let a=Math.max(1,Math.ceil(Math.max(0,t)/r));return Math.max(0,a-1-o)*80}function Ne(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 gi(n,e,t){let i=Ce(),r=!t&&we(e,i)?Te(n):null,o=Ee(e,i,r?.rowWidths??null,r?.gridWidth??null);return n.style.gridTemplateColumns=o.template,n.style.setProperty("--aia-grid-max-height",o.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((a,s)=>{a.classList.toggle("magicx-aia-option--scroll-hint",!t&&o.scrollHintIndices.includes(s))}),o.cols}function fn(n,e,t,i,r,o,a,s="",d="below"){let l=n.querySelector(".aia-grid");if(e.length===0){l?.remove();return}l||(l=document.createElement("div"),l.className="aia-grid magicx-aia-grid",l.setAttribute("data-scroll",""),l.style.setProperty("--aia-grid-min","250px"),l.style.setProperty("--aia-grid-max","1fr"),l.style.setProperty("--aia-grid-gap","0"),n.appendChild(l));let c=l.dataset.aiaGroup!==s;l.dataset.aiaGroup=s,hi(l,e,t,i,r,o,a);let u=gi(l,e.length,a);bi(l,e.length,u,a,d),c&&(l.scrollTop=0)}function hi(n,e,t,i,r,o,a){let s=a?"1":"0",d=n.dataset.aiaGroup??"";k(n,e,{keyOf:l=>`${l.text}\0${s}\0${d}`,create:(l,c)=>{let u=xi(l,a);return a||(u.dataset.aiaEntering=""),u},update:(l,c,u)=>{let p=u===t&&!a;l.id=`${o}-option-${u}`,l.dataset.aiaIndex=String(u),l.setAttribute("aria-selected",String(p)),l.classList.toggle("magicx-aia-option--highlighted",p),!a&&c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(c),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let g=Number.parseInt(l.dataset.aiaIndex??"-1",10);g>=0&&r(g)}):(l.onclick=null,l.onmouseenter=null)}})}function bi(n,e,t,i,r){for(let o of n.querySelectorAll("[data-aia-entering]")){if(!i){let a=Number.parseInt(o.dataset.aiaIndex??"-1",10);a>=0&&o.style.setProperty(Re,`${_e(a,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function xi(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("span");r.className="magicx-aia-option-content";let o=document.createElement("span");if(o.className="magicx-aia-option-text",o.textContent=n.icon?`${n.icon} ${n.text}`:n.text,r.appendChild(o),n.tag){let a=document.createElement("span");a.className="magicx-aia-option-tag",a.textContent=n.tag,r.appendChild(a)}return t.appendChild(r),t}var ut="magicx-aia-scroll-arrow",pt="data-aia-scroll-arrow",He="data-aia-visible",mt="--aia-scroll-arrow-bottom",ft="Scroll down for more options",yi=4,Si=8,vi=240;function Pi(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,a=n.ownerDocument?.visibilityState==="hidden";if(!o||a||hn(n)){n.scrollTop=r+e,i();return}let s=t.performance?.now?.()??Date.now(),d=()=>t.performance?.now?.()??Date.now(),l=()=>{let c=Math.min(1,(d()-s)/vi),u=1-(1-c)*(1-c);n.scrollTop=r+e*u,c<1?o.call(t,l):i()};o.call(t,l)}function wi(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","14"),t.setAttribute("height","14"),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 gn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=ut,e.setAttribute(pt,""),e.setAttribute("aria-label",ft),e.setAttribute("aria-hidden","true"),e.appendChild(wi(n)),e}function Ei(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function hn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Fe({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),r=!1,o=null,a=null,s=y=>{y?(t.setAttribute(He,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(He),t.setAttribute("aria-hidden","true"))},d=()=>{let y=0,x=e;for(;x&&x!==n;)y+=x.offsetTop,x=x.offsetParent instanceof HTMLElement?x.offsetParent:null;let m=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0,f=n.clientHeight-(y+e.offsetHeight)+(m>0?0:Si);t.style.setProperty(mt,`${Math.max(0,Math.round(f))}px`)},l=()=>{if(r||a!==null)return;let y=e.querySelector("[data-aia-option][data-aia-loading]")!==null,x=e.scrollHeight-e.clientHeight-e.scrollTop;s(!y&&x>yi)},c=()=>{if(r)return;d();let y=e.getAttribute("data-aia-group")??"";if(y!==o){o=y,s(!1),a!==null&&clearTimeout(a);let x=e.querySelectorAll("[data-aia-option]").length,m=hn(e)?0:Ne(x,Ei(e));a=setTimeout(()=>{a=null,l()},m);return}l()},u=()=>l();e.addEventListener("scroll",u,{passive:!0});let p=y=>y.preventDefault(),g=()=>{let y=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,x=Math.max(1,e.clientHeight-y);Pi(e,x,i,l)};t.addEventListener("mousedown",p),t.addEventListener("click",g);let b=null;return i&&typeof i.ResizeObserver=="function"&&(b=new i.ResizeObserver(()=>{d(),l()}),b.observe(e)),c(),{update:c,destroy(){r||(r=!0,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",u),t.removeEventListener("mousedown",p),t.removeEventListener("click",g),b?.disconnect(),s(!1))}}}var Ti=[159,119,164];function Ge(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 Be=new WeakMap;function Ci(n,e){let t=Be.get(n);if(t||(t={button:gn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Be.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Fe({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function gt(n){let e=Be.get(n);e&&(e.controller?.destroy(),Be.delete(n))}function Ve(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:u,onSkip:p}=e,g=a.length>0,b=s&&g,y=t.length>0,x=e.products.length>0,m=r&&(y||b||o||x);if(m?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!m){ct(n,!1);return}x?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let h=e.showSkipButton&&g&&!e.isInputEmpty,S=b||o&&s||h,P=f.querySelector(".magicx-aia-pill-bar");if(S){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),f.insertBefore(P,f.firstChild));let O=P.querySelector(".magicx-aia-pill-scroll");O||(O=document.createElement("span"),O.className="magicx-aia-pill-scroll",O.setAttribute("data-aia-pill-scroll",""),P.insertBefore(O,P.firstChild)),ke(O,s?a:[],0,u,!0,o&&s,d),Ii(P,h,o||e.skipDisabled,a[0],p)}else P&&P.remove();let v=e.suggestions[0],A=v?`${v.type} ${v.text}`:"",F=e.formatType==="date";fn(f,F?[]:t,i,l,c,e.listboxId,o,A,e.optionsPosition??"below"),Ci(n,f.querySelector(".aia-grid")),sn(f,F?t:[],i,e.listboxId,F?e.dateView:null,e.selectedDateIso,{onSelect:l,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let w=f.querySelector(".magicx-aia-skeleton-bars");if(o&&!y){if(!w){w=document.createElement("div"),w.className="magicx-aia-skeleton-bars",w.setAttribute("data-aia-skeleton-bars","");for(let O of Ti){let Ye=document.createElement("span");Ye.className="magicx-aia-skeleton-bar",Ye.style.width=`${O}px`,w.appendChild(Ye)}f.appendChild(w)}}else w&&w.remove();dn(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),ct(n,!0);let Q=f.querySelector(".magicx-aia-footer")??Mi(),On=i>=0&&!!t[i]?.is_tappable;Oi(Q,Le(On,e.isInputEmpty)),Q.isConnected||f.appendChild(Q),Ai(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Ai(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 Ii(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",a=>a.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Oi(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function Mi(){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 r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=De(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),n.append(e),n}function bn(n,e){let t=Ge(e.listboxId);return n.appendChild(t),{dropdown:t}}function ht(n,e,t){Ve(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:M(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,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:e.editingIdentified?e.editingIdentified.iso:G(e.editingParam?.text),optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Di=6,Li=.3;function xn(n){return n<=0?"0px":`${(-Math.min(Li,2*Di/n)).toFixed(3)}px`}function $e(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:a}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",tn(e,s?o:"");let d=t.map(x=>`${x.type}:${x.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(d===l&&(i??"")===c&&(r??"")===u)return;let p=a?I(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let g=e.ownerDocument??document,b=g.createDocumentFragment(),y=0;for(let x of t)if(y+=x.value.length,x.type==="completed"){let m=g.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=x.param.id;let f=x.param.id===i,h=x.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];f&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),h&&S.push("magicx-aia-segment--editing"),m.className=S.join(" "),m.style.letterSpacing=xn(x.value.length),m.textContent=x.value,b.appendChild(m)}else if(x.type==="identified"){let m=g.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=x.param.id;let f=["magicx-aia-segment","magicx-aia-segment--completed"];x.param.id===r&&f.push("magicx-aia-segment--editing"),m.className=f.join(" "),m.style.letterSpacing=xn(x.value.length),m.textContent=x.value,b.appendChild(m)}else b.appendChild(g.createTextNode(x.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(y),p!=null&&T(e,Math.max(0,Math.min(p,y)))}var ki='<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 yn(){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=ki,n}function Ri(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Sn(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function vn(n,e){let{listboxId:t}=e,i=Ge(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Ri()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=yn(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let c=new AbortController,{signal:u}=c,p=!1,g=0,b=()=>{let m=J(a),h=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(h)},y=()=>{let m=(a.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let f=m.anchorNode;return!f||!a.contains(f)?null:(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||a.focus()},{signal:u}),a.addEventListener("input",()=>{p||(g=performance.now(),b(),e.handleCaretAfterInput(I(a)))},{signal:u});let x=a.ownerDocument??document;if(x.addEventListener("selectionchange",()=>{let m=x.getSelection();if(!m||m.rangeCount===0||!a.contains(m.anchorNode))return;let f=m.isCollapsed?y():null,h=e.store.get(),S=h.editingParam?.id??h.editingIdentified?.id??null;if(f&&f!==S){e.startEditingParam(f);return}performance.now()-g<50||e.handleCaretMove(I(a))},{signal:u}),a.addEventListener("compositionstart",()=>{p=!0},{signal:u}),a.addEventListener("compositionend",()=>{p=!1,b()},{signal:u}),a.addEventListener("beforeinput",m=>{let f=m,h=f.inputType;if(h==="insertParagraph"||h==="insertLineBreak"||h==="insertFromDrop"){m.preventDefault();return}if(h.startsWith("insert")||h.startsWith("delete")){let S=h.startsWith("delete")?"":f.data??"";e.replaceEditingRange(S)&&m.preventDefault()}},{signal:u}),a.addEventListener("paste",m=>{m.preventDefault();let f=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let h=a.ownerDocument??document,S=h.getSelection();if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let v=h.createTextNode(f);P.insertNode(v),P.setStartAfter(v),P.collapse(!0),S.removeAllRanges(),S.addRange(P),b()},{signal:u}),a.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:u}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),l&&l.addEventListener("click",m=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation(),e.onSubmit(K(f.text,f.completedParams,f.skippedParams))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){a.focus();let m=a.ownerDocument??document,f=m.getSelection(),h=f&&f.rangeCount>0&&a.contains(f.anchorNode);if(f&&!h){let S=m.createRange();S.selectNodeContents(a),S.collapse(!0),f.removeAllRanges(),f.addRange(S)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Sn(a,s));m.observe(a),c.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:i,submitButton:d,abort:c}}function bt(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:a}=n,{pillPlacement:s,setActivePill:d,selectOption:l,store:c}=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"),a){let x=!!e.text||e.completedParams.length>0;a.disabled=!x}let p=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==p;if($e({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let x=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;x||e.actionableSuggestions.length>0?ke(r,e.actionableSuggestions,0,d,!1,x,e.isActivePillSelected):dt(r)}else dt(r);Sn(i,r),g?(i.focus(),T(i,e.caretOffset??e.text.length)):e.isFocused&&J(i)!==e.text&&T(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:M(e.editingIdentified.type),required:!0,options:[]}:null,y=b??e.actionableSuggestions[0];Ve(o,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:b?[b]:e.actionableSuggestions,showPills:s==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:e.editingIdentified?e.editingIdentified.iso:G(e.editingParam?.text),optionsPosition:t.optionsPosition??"below",onSelect:l,onHighlight:x=>c.set({activeDropdownIndex:x}),onPillClick:d,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:x=>c.set({isFocused:x})})}function Pn(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,a=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||a)&&n.placeholderText&&(r=`${n.placeholderText} `);let s=Lt(r,e.text);s>0&&(r=r.slice(0,r.length-s));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,c=(o||a)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=u>=0?c.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:p,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},b=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:c.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 We(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},i.push([e,s]),!r){r=!0;try{let d=0;for(let l=i.shift();l;l=i.shift()){if(++d>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[c,u]=l;for(let p of t)p(c,u)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function wn(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(a=>{let s={...a,...r(a)};return o(s)}):n.set(o)},peek:o=>{let a={...n.get(),...o};return{...a,...e(a)}},subscribe:o=>n.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var xt=!1;function En(){if(xt||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){xt=!0;return}xt=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=_i,document.head.appendChild(n)}var _i=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -245,12 +245,20 @@
245
245
  color: inherit;
246
246
  }
247
247
 
248
- /* Placeholder via ::before so it doesn't enter the editable DOM. */
248
+ /* Placeholder via ::before so it doesn't enter the editable DOM. The text is
249
+ typed in one character at a time by renderEditable's typewriter (the
250
+ attribute holds the typed prefix); the only fade is the outgoing phrase
251
+ when the placeholder changes \u2014 its duration mirrors PLACEHOLDER_FADE_OUT_MS. */
249
252
  .magicx-aia-input[data-aia-empty="true"][data-placeholder]::before {
250
253
  content: attr(data-placeholder);
251
254
  color: var(--aia-color-text-muted, #c1c4cb);
252
255
  opacity: 0.7;
253
256
  pointer-events: none;
257
+ transition: opacity var(--aia-placeholder-fade, 120ms) ease-out;
258
+ }
259
+
260
+ .magicx-aia-input[data-aia-placeholder-leaving]::before {
261
+ opacity: 0;
254
262
  }
255
263
 
256
264
  /* Inline pill list container \u2014 a non-editable sibling of the editable that
@@ -326,7 +334,17 @@
326
334
  z-index: 10;
327
335
  opacity: 0;
328
336
  pointer-events: none;
329
- transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
337
+ /* Closed, the panel rests as a near-zero-height sliver at the input's edge
338
+ (scaleY only \u2014 full width), so opening unfolds it top-to-bottom out of the
339
+ input. The origin flips to the bottom edge for optionsPosition="above" \u2014
340
+ see appearance.css. The transform "transition" on THIS side is a delayed
341
+ snap: while closing, the panel holds its full size for the whole 400ms
342
+ fade and only then collapses, ready for the next open. */
343
+ transform-origin: 50% 0;
344
+ transform: scaleY(var(--aia-dropdown-reveal-scale, 0.02));
345
+ transition:
346
+ opacity 400ms cubic-bezier(0.4, 0, 0.2, 1),
347
+ transform 0s 400ms;
330
348
  /* Solid surface is the default (matches the Figma components). Opt into the
331
349
  frosted-glass look with data-aia-surface="glass". */
332
350
  background: var(--aia-surface, #ffffff);
@@ -352,9 +370,20 @@
352
370
  backdrop-filter: blur(30px);
353
371
  }
354
372
 
373
+ /* Opening: the panel unfolds top-to-bottom out of the input with a single
374
+ spring settle while the option rows cascade in on top of it. Closing keeps
375
+ the longer fade so a populated panel dissolves as one (the base rule above
376
+ delays the transform snap until that fade has finished). */
355
377
  .magicx-aia-dropdown--visible {
356
378
  opacity: 1;
357
379
  pointer-events: auto;
380
+ transform: scaleY(1);
381
+ /* Spring: the easing overshoots full height by a few percent and settles
382
+ once (P1y = 1.28 \u2014 one spring, no bounce). Opacity resolves almost
383
+ immediately so the unfold, not a fade, is what reads. */
384
+ transition:
385
+ opacity 100ms cubic-bezier(0.4, 0, 0.2, 1),
386
+ transform 320ms cubic-bezier(0.22, 1.28, 0.36, 1);
358
387
  }
359
388
 
360
389
  /* --- Pill bar (inside dropdown) ---
@@ -634,6 +663,55 @@
634
663
  );
635
664
  }
636
665
 
666
+ /* --- "More below" scroll arrow (see render/scrollArrow.ts) ---
667
+ A round disc at the bottom-centre of the option list, shown while the list
668
+ can still scroll down. It rests just above the grid's reserved band
669
+ (--aia-scroll-arrow-bottom is measured and set inline by the controller so
670
+ it tracks the grid's bottom edge in every layout) and hides by sliding down
671
+ past the dropdown's lower edge, where the dropdown's overflow clips it \u2014 so
672
+ it emerges from behind the footer the way the reference's rises from behind
673
+ its composer. z-index 2 puts it over the option rows and under the footer
674
+ (z-index 3). Declarations mirror React's .scrollArrow and Angular's copy \u2014
675
+ change all three in the same commit. */
676
+ .magicx-aia-scroll-arrow {
677
+ position: absolute;
678
+ left: 50%;
679
+ bottom: var(--aia-scroll-arrow-bottom, 8px);
680
+ z-index: 2;
681
+ display: inline-flex;
682
+ align-items: center;
683
+ justify-content: center;
684
+ width: 32px;
685
+ height: 32px;
686
+ margin: 0 0 0 -16px;
687
+ padding: 0;
688
+ border: 1px solid
689
+ var(--aia-scroll-arrow-border, var(--aia-dropdown-border, rgba(231, 231, 231, 0.5)));
690
+ border-radius: 50%;
691
+ background: var(--aia-scroll-arrow-bg, var(--aia-surface, #ffffff));
692
+ color: var(
693
+ --aia-scroll-arrow-color,
694
+ var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb))
695
+ );
696
+ box-shadow: var(--aia-scroll-arrow-shadow, 0 2px 8px rgba(0, 0, 0, 0.12));
697
+ cursor: pointer;
698
+ pointer-events: none;
699
+ transform: translateY(calc(100% + var(--aia-scroll-arrow-bottom, 8px) + 4px));
700
+ transition: transform 180ms cubic-bezier(0.4, 0, 0.2, 1);
701
+ }
702
+
703
+ .magicx-aia-scroll-arrow[data-aia-visible] {
704
+ pointer-events: auto;
705
+ transform: translateY(0);
706
+ }
707
+
708
+ .magicx-aia-scroll-arrow:hover {
709
+ color: var(
710
+ --aia-scroll-arrow-color-hover,
711
+ var(--aia-option-color-selected, var(--aia-color-text-default, #fff))
712
+ );
713
+ }
714
+
637
715
  /* --- Footer (keyboard hint + AI-Autocomplete branding) ---
638
716
  The footer insets its own 8px horizontally so it stays clear of the
639
717
  dropdown's rounded edges. The top inset (--aia-footer-gap) adds breathing
@@ -643,7 +721,11 @@
643
721
  display: flex;
644
722
  flex-direction: column;
645
723
  gap: 8px;
646
- padding: var(--aia-footer-gap, 8px) 8px 0;
724
+ /* No right inset: the brand pill's own padding (below) supplies it, so the
725
+ badge sits as far from the right edge as it does from the bottom \u2014 12px
726
+ both ways (dropdown padding 10 + pill 2 down, dropdown padding 8 + pill 4
727
+ across). */
728
+ padding: var(--aia-footer-gap, 8px) 0 0 8px;
647
729
  /* The fade itself lives in appearance.css, on the footer's background.
648
730
  Paints above the rows it covers: option content sits at z-index 2 (see
649
731
  .magicx-aia-option-content) in this same stacking context, so anything
@@ -719,7 +801,7 @@
719
801
  .magicx-aia-footer-brand-link {
720
802
  background: var(--aia-footer-brand-pill-bg, var(--aia-surface, #ffffff));
721
803
  border-radius: 999px;
722
- padding: 2px 7px;
804
+ padding: 2px 4px;
723
805
  gap: 4px;
724
806
  }
725
807
 
@@ -911,7 +993,14 @@
911
993
  SuggestionItem selection. The 9px/10px inset is the item's own padding. */
912
994
  border-radius: 8px;
913
995
  padding: 8px 10px;
914
- animation: magicx-aia-optionFadeIn 500ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
996
+ /* Entrance: fade in while rising into place, each row a beat after the one
997
+ before it (--aia-option-enter-delay is set inline per row from the core's
998
+ optionEnterDelayMs). The durations and distance mirror OPTION_ENTER_* in
999
+ derive/optionsEntrance.ts \u2014 change both together. */
1000
+ animation:
1001
+ magicx-aia-optionFadeIn 150ms ease-out both,
1002
+ magicx-aia-optionRiseIn 280ms cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
1003
+ animation-delay: var(--aia-option-enter-delay, 0ms);
915
1004
  }
916
1005
 
917
1006
  @keyframes magicx-aia-optionFadeIn {
@@ -920,6 +1009,12 @@
920
1009
  }
921
1010
  }
922
1011
 
1012
+ @keyframes magicx-aia-optionRiseIn {
1013
+ from {
1014
+ transform: translateY(16px);
1015
+ }
1016
+ }
1017
+
923
1018
  .magicx-aia-option-content {
924
1019
  position: relative;
925
1020
  z-index: 2;
@@ -943,250 +1038,41 @@
943
1038
  font-weight: 500;
944
1039
  }
945
1040
 
1041
+ /* Press feedback: the picked option's text compresses down while every other
1042
+ option steps back in opacity \u2014 no fill, no glow, the hierarchy carries it. */
946
1043
  .magicx-aia-option--pressed {
947
- opacity: 0.8;
948
1044
  color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
949
- background: rgba(var(--aia-streak-rgb, 255, 255, 255), 0.06);
950
- animation:
951
- magicx-aia-glassFade 500ms ease forwards,
952
- magicx-aia-tapDown 500ms ease forwards;
953
- }
954
-
955
- @keyframes magicx-aia-tapDown {
956
- 0% {
957
- transform: scale(1);
958
- }
959
- 30% {
960
- transform: scale(0.97);
961
- }
962
- 100% {
963
- transform: scale(1);
964
- }
965
- }
966
-
967
- @keyframes magicx-aia-glassFade {
968
- 0% {
969
- background: var(--aia-streak-glass-bg, rgba(255, 255, 255, 0.1));
970
- }
971
- 100% {
972
- background: transparent;
973
- }
974
- }
975
-
976
- /* --- Streak animations --- */
977
- .magicx-aia-streaks {
978
- position: absolute;
979
- inset: 0;
980
- z-index: 1;
981
- pointer-events: none;
982
- border-radius: inherit;
983
- overflow: hidden;
984
- }
985
-
986
- .magicx-aia-streaks::before {
987
- content: "";
988
- position: absolute;
989
- bottom: -3px;
990
- left: 60%;
991
- width: 0;
992
- height: 6px;
993
- opacity: 0;
994
- background: radial-gradient(
995
- ellipse at center,
996
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.5) 0%,
997
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.2) 40%,
998
- transparent 70%
999
- );
1000
- box-shadow: 0 0 12px 4px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.2);
1001
- filter: blur(1px);
1002
- border-radius: 50%;
1003
- }
1004
-
1005
- .magicx-aia-streaks::after {
1006
- content: "";
1007
- position: absolute;
1008
- top: -3px;
1009
- right: 60%;
1010
- width: 0;
1011
- height: 6px;
1012
- opacity: 0;
1013
- background: radial-gradient(
1014
- ellipse at center,
1015
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.5) 0%,
1016
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.2) 40%,
1017
- transparent 70%
1018
- );
1019
- box-shadow: 0 0 12px 4px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.2);
1020
- filter: blur(1px);
1021
- border-radius: 50%;
1022
- }
1023
-
1024
- .magicx-aia-streaks-vert {
1025
- position: absolute;
1026
- inset: 0;
1027
- z-index: 1;
1028
- pointer-events: none;
1029
- border-radius: inherit;
1030
- overflow: hidden;
1045
+ animation: magicx-aia-pressCompress 500ms ease forwards;
1031
1046
  }
1032
1047
 
1033
- .magicx-aia-streaks-vert::before {
1034
- content: "";
1035
- position: absolute;
1036
- bottom: 0;
1037
- right: -3px;
1038
- width: 6px;
1039
- height: 0;
1040
- opacity: 0;
1041
- background: radial-gradient(
1042
- ellipse at center,
1043
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.4) 0%,
1044
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.15) 40%,
1045
- transparent 70%
1046
- );
1047
- box-shadow: 0 0 12px 4px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.15);
1048
- filter: blur(1px);
1049
- border-radius: 50%;
1050
- }
1051
-
1052
- .magicx-aia-streaks-vert::after {
1053
- content: "";
1054
- position: absolute;
1055
- top: 0;
1056
- left: -3px;
1057
- width: 6px;
1058
- height: 0;
1059
- opacity: 0;
1060
- background: radial-gradient(
1061
- ellipse at center,
1062
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.4) 0%,
1063
- rgba(var(--aia-streak-rgb, 255, 255, 255), 0.15) 40%,
1064
- transparent 70%
1065
- );
1066
- box-shadow: 0 0 12px 4px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.15);
1067
- filter: blur(1px);
1068
- border-radius: 50%;
1069
- }
1070
-
1071
- .magicx-aia-option--pressed .magicx-aia-streaks::before {
1072
- animation: magicx-aia-streakHorizRight 500ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
1073
- }
1074
- .magicx-aia-option--pressed .magicx-aia-streaks::after {
1075
- animation: magicx-aia-streakHorizLeft 500ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
1076
- }
1077
- .magicx-aia-option--pressed .magicx-aia-streaks-vert::before {
1078
- animation: magicx-aia-streakVertUp 300ms cubic-bezier(0.3, 0, 0.2, 1) 200ms forwards;
1079
- }
1080
- .magicx-aia-option--pressed .magicx-aia-streaks-vert::after {
1081
- animation: magicx-aia-streakVertDown 300ms cubic-bezier(0.3, 0, 0.2, 1) 200ms forwards;
1082
- }
1083
-
1084
- @keyframes magicx-aia-streakHorizRight {
1085
- 0% {
1086
- width: 0;
1087
- height: 4px;
1088
- opacity: 0;
1089
- filter: blur(1px);
1090
- box-shadow: 0 0 8px 3px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.3);
1091
- }
1092
- 15% {
1093
- height: 4px;
1094
- opacity: 1;
1095
- filter: blur(1px);
1096
- box-shadow: 0 0 10px 4px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.3);
1097
- }
1098
- 80% {
1099
- width: 50%;
1100
- height: 10px;
1101
- opacity: 0.8;
1102
- filter: blur(3px);
1103
- box-shadow: 0 0 16px 6px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.1);
1104
- }
1105
- 100% {
1106
- width: 50%;
1107
- height: 12px;
1108
- opacity: 0;
1109
- filter: blur(5px);
1110
- box-shadow: 0 0 20px 8px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.03);
1111
- }
1048
+ [role="listbox"]:has(.magicx-aia-option--pressed)
1049
+ .magicx-aia-option:not(.magicx-aia-option--pressed) {
1050
+ opacity: 0.35;
1051
+ transition: opacity 150ms ease;
1112
1052
  }
1113
1053
 
1114
- @keyframes magicx-aia-streakHorizLeft {
1054
+ @keyframes magicx-aia-pressCompress {
1115
1055
  0% {
1116
- width: 0;
1117
- height: 4px;
1118
- opacity: 0;
1119
- filter: blur(1px);
1120
- box-shadow: 0 0 8px 3px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.3);
1056
+ transform: scale(1);
1121
1057
  }
1122
- 15% {
1123
- height: 4px;
1124
- opacity: 1;
1125
- filter: blur(1px);
1126
- box-shadow: 0 0 10px 4px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.3);
1058
+ 25% {
1059
+ transform: scale(0.93);
1127
1060
  }
1128
- 80% {
1129
- width: 50%;
1130
- height: 10px;
1131
- opacity: 0.8;
1132
- filter: blur(3px);
1133
- box-shadow: 0 0 16px 6px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.1);
1061
+ 60% {
1062
+ transform: scale(0.93);
1134
1063
  }
1135
1064
  100% {
1136
- width: 50%;
1137
- height: 12px;
1138
- opacity: 0;
1139
- filter: blur(5px);
1140
- box-shadow: 0 0 20px 8px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.03);
1065
+ transform: scale(1);
1141
1066
  }
1142
1067
  }
1143
1068
 
1144
- @keyframes magicx-aia-streakVertUp {
1145
- 0% {
1146
- height: 0;
1147
- width: 6px;
1148
- opacity: 0.9;
1149
- filter: blur(1.8px);
1150
- box-shadow: 0 0 12px 5px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.25);
1151
- }
1152
- 75% {
1153
- height: 100%;
1154
- width: 10px;
1155
- opacity: 0.4;
1156
- filter: blur(3px);
1157
- box-shadow: 0 0 18px 8px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.06);
1158
- }
1159
- 100% {
1160
- height: 100%;
1161
- width: 14px;
1162
- opacity: 0;
1163
- filter: blur(5px);
1164
- box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
1165
- }
1166
- }
1167
-
1168
- @keyframes magicx-aia-streakVertDown {
1169
- 0% {
1170
- height: 0;
1171
- width: 6px;
1172
- opacity: 0.9;
1173
- filter: blur(1.8px);
1174
- box-shadow: 0 0 12px 5px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.25);
1175
- }
1176
- 75% {
1177
- height: 100%;
1178
- width: 10px;
1179
- opacity: 0.4;
1180
- filter: blur(3px);
1181
- box-shadow: 0 0 18px 8px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.06);
1182
- }
1183
- 100% {
1184
- height: 100%;
1185
- width: 14px;
1186
- opacity: 0;
1187
- filter: blur(5px);
1188
- box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
1189
- }
1069
+ /* Scroll hint \u2014 the last visible row of a scrollable web grid fades toward its
1070
+ bottom edge, signalling more options below (the desktop footer is opaque, so
1071
+ rows no longer dissolve through it). A mask instead of a color so any themed
1072
+ option color fades the same way. */
1073
+ .magicx-aia-option--scroll-hint .magicx-aia-option-content {
1074
+ -webkit-mask-image: linear-gradient(to bottom, rgb(0 0 0), rgb(0 0 0 / 0.6));
1075
+ mask-image: linear-gradient(to bottom, rgb(0 0 0), rgb(0 0 0 / 0.6));
1190
1076
  }
1191
1077
 
1192
1078
  /* --- Promotion reveal ---
@@ -1211,11 +1097,22 @@
1211
1097
  because the panel's darkness comes from --aia-surface, which the media query
1212
1098
  says nothing about. Going through the option chain means one consumer
1213
1099
  override restyles the calendar and the options together. */
1100
+ /* A calendar has nothing wide to read, so the whole panel narrows with it \u2014
1101
+ the option grid's 544px cap leaves a month floating in empty panel. The
1102
+ :has() argument is the datepicker's data attribute, which all three packages
1103
+ emit identically; only the panel class differs per copy. */
1104
+ .magicx-aia-dropdown:has([data-aia-datepicker]) {
1105
+ max-width: var(--aia-date-panel-width, 312px);
1106
+ }
1107
+
1214
1108
  .magicx-aia-datepicker {
1215
1109
  display: flex;
1216
1110
  flex-direction: column;
1217
1111
  gap: 4px;
1218
- padding: 4px 2px 8px;
1112
+ /* Bottom-heavier trim than the top: the compression the compact calendar
1113
+ asks for comes out of the bottom edge and the space between cells, never
1114
+ the header area or the side gutters. */
1115
+ padding: 4px 2px 4px;
1219
1116
  }
1220
1117
 
1221
1118
  .magicx-aia-datepicker-header {
@@ -1293,9 +1190,9 @@
1293
1190
  min-width: 0;
1294
1191
  /* Keeps a month readable in a narrow dropdown without letting a 6-row month
1295
1192
  grow the panel past the options grid it replaces. */
1296
- height: var(--aia-date-row-height, 40px);
1193
+ height: var(--aia-date-row-height, 28px);
1297
1194
  font-family: inherit;
1298
- font-size: var(--aia-date-cell-font-size, 14px);
1195
+ font-size: var(--aia-date-cell-font-size, 13px);
1299
1196
  font-weight: 450;
1300
1197
  line-height: 20px;
1301
1198
  color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
@@ -1307,9 +1204,9 @@
1307
1204
  display: flex;
1308
1205
  align-items: center;
1309
1206
  justify-content: center;
1310
- width: var(--aia-date-cell-size, 36px);
1311
- height: var(--aia-date-cell-size, 36px);
1312
- border-radius: 8px;
1207
+ width: var(--aia-date-cell-size, 26px);
1208
+ height: var(--aia-date-cell-size, 26px);
1209
+ border-radius: 6px;
1313
1210
  }
1314
1211
 
1315
1212
  .magicx-aia-date-cell--day {
@@ -1320,6 +1217,12 @@
1320
1217
  cursor: default;
1321
1218
  }
1322
1219
 
1220
+ /* A day before today: dimmed so the month visibly starts at today, but still
1221
+ fully interactive \u2014 hover and click behave like any other day. */
1222
+ .magicx-aia-date-cell--past {
1223
+ opacity: 0.35;
1224
+ }
1225
+
1323
1226
  .magicx-aia-date-cell--day:hover .magicx-aia-date-cell-number,
1324
1227
  .magicx-aia-date-cell--highlighted .magicx-aia-date-cell-number {
1325
1228
  color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
@@ -1345,6 +1248,20 @@
1345
1248
  background: rgba(var(--aia-streak-rgb, 255, 255, 255), 0.06);
1346
1249
  }
1347
1250
 
1251
+ /* Reduced motion: the entrance choreography and the arrow's slide collapse to
1252
+ instant (the placeholder typewriter checks the same preference in JS). The
1253
+ rest of the SDK's motion is left as-is \u2014 it predates this block. */
1254
+ @media (prefers-reduced-motion: reduce) {
1255
+ .magicx-aia-option,
1256
+ .magicx-aia-scroll-arrow,
1257
+ .magicx-aia-dropdown,
1258
+ .magicx-aia-input[data-aia-empty="true"][data-placeholder]::before {
1259
+ animation-duration: 0s;
1260
+ animation-delay: 0s;
1261
+ transition-duration: 0s;
1262
+ }
1263
+ }
1264
+
1348
1265
  /*
1349
1266
  * Built-in appearance defaults \u2014 zero specificity via :where().
1350
1267
  * Consumer CSS always wins without !important.
@@ -1407,8 +1324,8 @@
1407
1324
  --aia-border: rgba(17, 24, 39, 0.14); /* subtle slate hairline (off-palette) */
1408
1325
  /* Elevation for the input container (.magicx-aia-input-wrapper). */
1409
1326
  --aia-shadow:
1410
- inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 1px 2px rgba(16, 24, 40, 0.1),
1411
- 0 8px 24px rgba(16, 24, 40, 0.16);
1327
+ inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 1px 2px rgba(16, 24, 40, 0.05),
1328
+ 0 8px 24px rgba(16, 24, 40, 0.08);
1412
1329
  /* Half-strength stroke: neutral-900 (was #e5e7eb \u2014 snapped to palette,
1413
1330
  \u03942) at 50% alpha over the surface, so the hairline lands exactly
1414
1331
  halfway between its old value and the white behind it. */
@@ -1451,7 +1368,6 @@
1451
1368
  --aia-skeleton-bg: var(--aia-primitive-neutral-750-a25);
1452
1369
 
1453
1370
  --aia-streak-rgb: 99, 102, 241; /* off shared palette (indigo effect) */
1454
- --aia-streak-glass-bg: rgba(99, 102, 241, 0.1);
1455
1371
 
1456
1372
  --aia-footer-hint-color: var(--aia-primitive-neutral-500);
1457
1373
  --aia-footer-brand-color: var(--aia-primitive-neutral-700);
@@ -1465,8 +1381,8 @@
1465
1381
  /* Elevation for the input container (.magicx-aia-input-wrapper) \u2014 tuned for
1466
1382
  dark surfaces: a faint top highlight + deeper ambient shadows. */
1467
1383
  --aia-shadow:
1468
- inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px rgba(0, 0, 0, 0.4),
1469
- 0 8px 24px rgba(0, 0, 0, 0.5);
1384
+ inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px rgba(0, 0, 0, 0.2),
1385
+ 0 8px 24px rgba(0, 0, 0, 0.25);
1470
1386
  /* Half-strength stroke \u2014 neutral-400 (was #484848 \u2014 snapped to palette,
1471
1387
  \u03942) at 50% alpha; see the light-mode note above. */
1472
1388
  --aia-dropdown-border: var(--aia-primitive-neutral-400-a50);
@@ -1506,7 +1422,6 @@
1506
1422
  --aia-skeleton-bg: var(--aia-primitive-neutral-150);
1507
1423
 
1508
1424
  --aia-streak-rgb: 255, 255, 255;
1509
- --aia-streak-glass-bg: rgba(255, 255, 255, 0.1);
1510
1425
 
1511
1426
  --aia-footer-hint-color: var(--aia-primitive-neutral-700);
1512
1427
  --aia-footer-brand-color: var(--aia-primitive-neutral-500);
@@ -1623,6 +1538,9 @@
1623
1538
  --aia-grid-scroll-top: var(--aia-footer-band);
1624
1539
  --aia-grid-overlap-top: calc(-1 * (var(--aia-footer-band) + 8px));
1625
1540
  --aia-footer-fade-inset: 0 0 calc(-1 * var(--aia-footer-fade-lead));
1541
+ /* The unfold flips with the stack: the collapsed sliver sits at the panel's
1542
+ bottom edge (against the input) and expands upward out of it. */
1543
+ transform-origin: 50% 100%;
1626
1544
  top: auto;
1627
1545
  bottom: 100%;
1628
1546
  margin-top: 0;
@@ -1636,7 +1554,7 @@
1636
1554
  /* The footer now sits on top of the list, so its breathing room flips to the
1637
1555
  bottom edge \u2014 the side the option rows scroll under. */
1638
1556
  :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] [data-aia-footer] {
1639
- padding: 0 8px var(--aia-footer-gap, 8px);
1557
+ padding: 0 0 var(--aia-footer-gap, 8px) 8px;
1640
1558
  }
1641
1559
 
1642
1560
  /* ...and the fade runs the other way, out of the footer and down into the list. */
@@ -1651,5 +1569,20 @@
1651
1569
  animation-duration: 0s !important;
1652
1570
  transition-duration: 0s !important;
1653
1571
  }
1654
- `;var Me=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(r){return this.report(e,r,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 Le=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...a)=>t(...a);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ne=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}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 V=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 Bn(n){return(n??re).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function $n(n){return j(n)?`Bearer ${await oe(n).getToken()}`:ae(n)}async function Ht(n){try{let e=Bn(n.apiConfig?.endpoint),t=se(n.apiConfig),i=await $n(n.apiConfig);i&&(t.Authorization=i);let r=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:r})}catch{}}var Kn="newParam",Bt="suggestionRemoval",Vn="selectionAnimation",Un=650,Gn=0;function qn(){return`:ac-${++Gn}:`}var $t=500;function Kt(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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,editingIdentified:null}}var Re=class{constructor(e,t={}){this.inputStore=ke(Kt());this._listboxId=qn();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ne;this.boundary=new Me;this.subscriberCount=0;this.emitter=new Le(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=_t(this.inputStore,i=>Pt(i,this.deriveOpts())),t.onSubmit&&this.emitter.on("submit",t.onSubmit),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 be(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Ce({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new xe(this.store,()=>this.opts.products),this.fetchController=new ce(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new he(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,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.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,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:a}=de(i.text,i.completedParams,i.identifiedParams);a.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.identifiedParams===r.identifiedParams)return;let o=i.editingIdentified;if(!o||i.identifiedParams.some(l=>l.id===o.id))return;let a=0,s;for(let l of i.segments){if(l.type==="identified"&&a===o.anchor&&l.value===o.text){s=l.param;break}a+=l.value.length}if(s){this.store.set({editingIdentified:{...o,id:s.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let a=o.anchor;if(i.text!==r.text){let l=ft(r.text,i.text,a);if(l===null){this.store.set({pendingSpan:null});return}a=l}i.text.slice(a).trim().length===0||pt(i.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(Ft(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...Kt(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.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=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 r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,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:r,end:o}=t;if(e===o){let{text:l,removed:d}=we(i,r,o);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let a=ge(i,e),s=i.slice(0,a)+i.slice(e);return this.store.set(l=>({text:s,filterBase:Math.min(l.filterBase,s.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!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(),E(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(s=>s.id===e);if(!i||D(i)!=="date")return!1;let r=0,o=-1;for(let s of t.segments){if(s.type!=="text"&&s.param.id===e){o=r;break}r+=s.value.length}if(o<0)return!1;let a=o+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:o,tail:a,text:i.text,iso:ne(i)},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:a,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(t.activeFormatType!=="date"||!t.dateView)return;let i=J(t.dateView,e);this.store.set({dateViewMonth:{...i,key:Ge(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}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;Object.assign(this.opts,e),"products"in e&&e.products!==t&&this.productsController.clearNow(),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)&&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.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Rt(t,e);if(i){if(this.fireTelemetry("option",{raw_query:C(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:t.activeFormatType==="date"?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Bt),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(Bt,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},$t)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Vn,()=>this.store.set({inSelectionAnimation:!1}),$t)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ht({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[i,r]of Object.entries(e))t[i]=o=>this.boundary.run(`optionOverrides.${i}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}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 V(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 onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=Nt(this.container,t);let i=()=>{this.domRefs&&Ye(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Ye(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},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Dt(this.container,t);let i=()=>{this.dropdownRefs&&je(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),je(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(z),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(Kn,()=>this.store.set({newParamId:null}),Un)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=bt(e,t.completedParams);r.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=k(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=ut(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(o=>o.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);R(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=C(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 r=t.text.slice(0,i.anchor),o=t.text.slice(i.tail),a=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,s=o.length===0||o[0]!==" ",l=s?`${a} `:a,d=r+l+o,c=i.anchor+l.length+(s?0:1),u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:a,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.type,options:[],metadata:e.metadata};this.fireTelemetry("option",{raw_query:C(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:d,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(p=>p.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(t.activeFormatType==="date")return;let i=Pe({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,ModeController,OPTIONS_GRID_MOBILE_QUERY,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,computeOptionsGridLayout,createStore,cursorIsAtEnd,extractPlainText,formatDate,getCursorOffset,getFooterHint,isOptionsGridMobileViewport,isoDate,monthLabel,optionsGridTemplateColumns,parseDate,parseLooseDate,plainTextLength,previousGraphemeBoundary,renderEditableContent,resolveFormatType,resolveIdentifiedDate,selectedIsoFromText,setCursorOffset,withSkippedParams});
1572
+
1573
+ /* Desktop footer is opaque: the option list clips at the footer's edge instead
1574
+ of showing through it \u2014 the scroll cue lives in the last visible row's own
1575
+ text instead (the option scroll-hint rule). Mobile keeps the fade. Declared
1576
+ last, and carrying the unwrapped above-position selector some copies use
1577
+ (so it ties that rule's higher specificity and wins on cascade order);
1578
+ the glass surface still hides this pseudo-element entirely. */
1579
+ @media (min-width: 769px) {
1580
+ [data-aia-dropdown] [data-aia-footer]::before,
1581
+ [data-aia-dropdown][data-options-position="above"] [data-aia-footer]::before,
1582
+ :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] [data-aia-footer]::before {
1583
+ inset: 0;
1584
+ background: var(--aia-surface, #ffffff);
1585
+ }
1586
+ }
1587
+ `;var Ke=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(r){return this.report(e,r,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 Ue=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...a)=>t(...a);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var qe=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}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 q=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 Ni(n){return(n??ae).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Hi(n){return X(n)?`Bearer ${await le(n).getToken()}`:ce(n)}async function Tn(n){try{let e=Ni(n.apiConfig?.endpoint),t=de(n.apiConfig),i=await Hi(n.apiConfig);i&&(t.Authorization=i);let r=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:r})}catch{}}var Fi="newParam",Cn="suggestionRemoval",Bi="selectionAnimation",Gi=650,Vi=0;function $i(){return`:ac-${++Vi}:`}var An=500;function In(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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,editingIdentified:null}}var Qe=class{constructor(e,t={}){this.inputStore=We(In());this._listboxId=$i();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new qe;this.boundary=new Ke;this.subscriberCount=0;this.emitter=new Ue(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=wn(this.inputStore,i=>Qt(i,this.deriveOpts())),t.onSubmit&&this.emitter.on("submit",t.onSubmit),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 ve(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Oe({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Pe(this.store,()=>this.opts.products),this.fetchController=new me(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new Se(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,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.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,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:a}=pe(i.text,i.completedParams,i.identifiedParams);a.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.identifiedParams===r.identifiedParams)return;let o=i.editingIdentified;if(!o||i.identifiedParams.some(d=>d.id===o.id))return;let a=0,s;for(let d of i.segments){if(d.type==="identified"&&a===o.anchor&&d.value===o.text){s=d.param;break}a+=d.value.length}if(s){this.store.set({editingIdentified:{...o,id:s.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let a=o.anchor;if(i.text!==r.text){let d=Ht(r.text,i.text,a);if(d===null){this.store.set({pendingSpan:null});return}a=d}i.text.slice(a).trim().length===0||_t(i.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(En(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...In(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.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&&(nn(this.domRefs.input),gt(this.domRefs.dropdown)),this.dropdownRefs&&gt(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 r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,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:r,end:o}=t;if(e===o){let{text:d,removed:l}=Ie(i,r,o);return this.store.set(c=>({text:d,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-l):c.filterBase,d.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let a=ye(i,e),s=i.slice(0,a)+i.slice(e);return this.store.set(d=>({text:s,filterBase:Math.min(d.filterBase,s.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!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(),T(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(s=>s.id===e);if(!i||D(i)!=="date")return!1;let r=0,o=-1;for(let s of t.segments){if(s.type!=="text"&&s.param.id===e){o=r;break}r+=s.value.length}if(o<0)return!1;let a=o+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:o,tail:a,text:i.text,iso:oe(i)},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:a,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(t.activeFormatType!=="date"||!t.dateView)return;let i=te(t.dateView,e);this.store.set({dateViewMonth:{...i,key:at(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}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;Object.assign(this.opts,e),"products"in e&&e.products!==t&&this.productsController.clearNow(),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)&&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.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Pn(t,e);if(i){if(this.fireTelemetry("option",{raw_query:E(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:t.activeFormatType==="date"?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Cn),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(Cn,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},An)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Bi,()=>this.store.set({inSelectionAnimation:!1}),An)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Tn({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[i,r]of Object.entries(e))t[i]=o=>this.boundary.run(`optionOverrides.${i}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}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 q(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 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:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=vn(this.container,t);let i=()=>{this.domRefs&&bt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),bt(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 optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=bn(this.container,t);let i=()=>{this.dropdownRefs&&ht(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),ht(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(Z),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(Fi,()=>this.store.set({newParamId:null}),Gi)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Gt(e,t.completedParams);r.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=L(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Rt(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(o=>o.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);N(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=E(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 r=t.text.slice(0,i.anchor),o=t.text.slice(i.tail),a=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=o.length===0||o[0]!==" "?`${a} `:a,l=r+d+o,c=l.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:a,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:M(i.type),options:[],metadata:e.metadata};this.fireTelemetry("option",{raw_query:E(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:l,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(p=>p.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(t.activeFormatType==="date")return;let i=Ae({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,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,SCROLL_ARROW_ATTR,SCROLL_ARROW_BOTTOM_VAR,SCROLL_ARROW_CLASS,SCROLL_ARROW_LABEL,SCROLL_ARROW_VISIBLE_ATTR,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,attachScrollArrow,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,computeOptionsGridLayout,createStore,cursorIsAtEnd,extractPlainText,formatDate,getCursorOffset,getFooterHint,identifiedParamLabel,isOptionsGridMobileViewport,isoDate,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionEnterDelayMs,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,plainTextLength,planOptionsGrid,previousGraphemeBoundary,renderEditableContent,resolveFormatType,resolveIdentifiedDate,scrollCaretIntoView,selectedIsoFromText,setCursorOffset,withSkippedParams});
1655
1588
  //# sourceMappingURL=index.js.map