@magicx-eng/ai-autocomplete-vanilla 0.15.0 → 0.16.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/README.md CHANGED
@@ -24,6 +24,7 @@ A framework-agnostic vanilla JS/TypeScript library that provides a guided AI-pow
24
24
  - **Loading skeleton** — while a fetch is in flight, the dropdown and inline pills keep the previous layout (same count and widths) with their text masked and a shimmer pulse. The skeleton is held back until the option-press animation finishes, so taps don't visually "stutter" into loading.
25
25
  - **Lightweight** — ~10 KB gzipped, styles auto-injected at runtime
26
26
  - **TypeScript first** — full type definitions shipped with the package
27
+ - **Shadow-DOM ready** — mount the container inside a shadow root and the styles and caret follow it there, with nothing to configure; page CSS can't reach the widget
27
28
  - **SSR-safe** — no top-level `document`/`window` access
28
29
 
29
30
  ## Installation
@@ -91,6 +92,11 @@ const ac = new AIAutocomplete(container, {
91
92
  // Focus
92
93
  autoFocus: true, // focus the input on mount (Tier 1 only)
93
94
 
95
+ // Where the stylesheet is injected. Defaults to the container's own root —
96
+ // the document, or the shadow root when the widget is mounted in one — so
97
+ // this is only for sending the styles somewhere else. See "Shadow DOM".
98
+ styleRoot: undefined,
99
+
94
100
  // Product strip (opt-in). Omit it and nothing changes: no request, no markup.
95
101
  products: {
96
102
  fetch: (query, signal) => myPlatform.search(query, { signal }),
@@ -593,6 +599,25 @@ Constructor callbacks (`onSubmit`, `onChange`, etc.) are registered once at cons
593
599
 
594
600
  Styles are auto-injected at runtime (Tier 1 and Tier 2). No CSS import needed. The component ships built-in light and dark defaults.
595
601
 
602
+ ### Shadow DOM
603
+
604
+ Mount the container inside a shadow root and the widget works there — the stylesheet is injected into that root rather than `document.head`, and the caret is read from the root that owns the editor:
605
+
606
+ ```js
607
+ const host = document.querySelector("#autocomplete-host");
608
+ const root = host.attachShadow({ mode: "open" });
609
+ const container = document.createElement("div");
610
+ root.appendChild(container);
611
+
612
+ const ac = new AIAutocomplete(container, { apiConfig: { apiKey: "..." } });
613
+ ```
614
+
615
+ Nothing to configure: the root is derived from the container. Light-DOM mounts are unaffected, and a page can hold both — each root gets the stylesheet.
616
+
617
+ This is the way to embed the widget in a page whose CSS you don't control. In the light DOM every page rule reaches the widget, and the ones that reach it by element (`footer`, `kbd`, `a`) or with `!important` win over the SDK's own classes. A shadow root ends that: page rules stop at the boundary. Note that the same boundary stops **your** page CSS too, so the [selector hooks](#selector-hooks) below have to be applied from inside the shadow root (or through the `--aia-*` variables, which inherit across it — set them on the host).
618
+
619
+ `styleRoot` overrides where the styles land, for the rare mount whose container root isn't where they should go. It's applied once, at construction.
620
+
596
621
  ### CSS Variables
597
622
 
598
623
  Override these on the container element. All built-in defaults use `:where()` (zero specificity) — your overrides always win without `!important`.
package/dist/index.d.mts CHANGED
@@ -530,6 +530,15 @@ interface CoreOptions {
530
530
  showSkipButton?: boolean;
531
531
  /** Render mode. Default: "full". */
532
532
  renderMode?: RenderMode;
533
+ /**
534
+ * Where the SDK's stylesheet is injected. Defaults to the root the container
535
+ * is mounted in — the document, or the shadow root when the widget is inside
536
+ * one — so mounting into a shadow root is styled correctly with no
537
+ * configuration. Set this only when the styles need to land somewhere else
538
+ * than the container's own root. Applied once at construction; ignored by
539
+ * `update()`, and by `renderMode: "headless"`, which injects no styles.
540
+ */
541
+ styleRoot?: Document | ShadowRoot;
533
542
  /**
534
543
  * Identifies which SDK surface is in use, for telemetry only. The hook can't
535
544
  * distinguish on its own — the Tier 1 component sets "full-sdk" when wiring
@@ -590,7 +599,7 @@ type AIAutocompleteEvents = {
590
599
  blur: [];
591
600
  productSelect: [product: Product];
592
601
  };
593
- type CoreUpdateOptions = Partial<Omit<CoreOptions, "onSubmit" | "onError" | "onChange" | "onParamsChange" | "onStateChange" | "onFocus" | "onBlur" | "onProductSelect">>;
602
+ type CoreUpdateOptions = Partial<Omit<CoreOptions, "onSubmit" | "onError" | "onChange" | "onParamsChange" | "onStateChange" | "onFocus" | "onBlur" | "onProductSelect" | "styleRoot">>;
594
603
  declare class AIAutocomplete {
595
604
  private inputStore;
596
605
  private store;
package/dist/index.d.ts CHANGED
@@ -530,6 +530,15 @@ interface CoreOptions {
530
530
  showSkipButton?: boolean;
531
531
  /** Render mode. Default: "full". */
532
532
  renderMode?: RenderMode;
533
+ /**
534
+ * Where the SDK's stylesheet is injected. Defaults to the root the container
535
+ * is mounted in — the document, or the shadow root when the widget is inside
536
+ * one — so mounting into a shadow root is styled correctly with no
537
+ * configuration. Set this only when the styles need to land somewhere else
538
+ * than the container's own root. Applied once at construction; ignored by
539
+ * `update()`, and by `renderMode: "headless"`, which injects no styles.
540
+ */
541
+ styleRoot?: Document | ShadowRoot;
533
542
  /**
534
543
  * Identifies which SDK surface is in use, for telemetry only. The hook can't
535
544
  * distinguish on its own — the Tier 1 component sets "full-sdk" when wiring
@@ -590,7 +599,7 @@ type AIAutocompleteEvents = {
590
599
  blur: [];
591
600
  productSelect: [product: Product];
592
601
  };
593
- type CoreUpdateOptions = Partial<Omit<CoreOptions, "onSubmit" | "onError" | "onChange" | "onParamsChange" | "onStateChange" | "onFocus" | "onBlur" | "onProductSelect">>;
602
+ type CoreUpdateOptions = Partial<Omit<CoreOptions, "onSubmit" | "onError" | "onChange" | "onParamsChange" | "onStateChange" | "onFocus" | "onBlur" | "onProductSelect" | "styleRoot">>;
594
603
  declare class AIAutocomplete {
595
604
  private inputStore;
596
605
  private store;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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 {
1
+ "use strict";var et=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Gn=Object.prototype.hasOwnProperty;var Vn=(n,e)=>{for(var t in e)et(n,t,{get:e[t],enumerable:!0})},$n=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Wn(e))!Gn.call(n,r)&&r!==t&&et(n,r,{get:()=>e[r],enumerable:!(i=Bn(e,r))||i.enumerable});return n};var Kn=n=>$n(et({},"__esModule",{value:!0}),n);var er={};Vn(er,{AIAutocomplete:()=>Je,ATTRIBUTION_URL:()=>mt,ModeController:()=>Y,OPTIONS_GRID_MOBILE_QUERY:()=>te,OPTION_ENTER_DELAY_VAR:()=>Be,OPTION_ENTER_FADE_MS:()=>hn,OPTION_ENTER_RISE_MS:()=>bn,OPTION_ENTER_RISE_PX:()=>xn,OPTION_ENTER_STAGGER_MS:()=>gn,PLACEHOLDER_FADE_OUT_MS:()=>nn,PLACEHOLDER_LEAVING_ATTR:()=>B,PLACEHOLDER_SWAP_GAP_MS:()=>rn,PLACEHOLDER_TYPE_MS:()=>en,PLACEHOLDER_WORD_PAUSE_MS:()=>tn,SCROLL_ARROW_ATTR:()=>bt,SCROLL_ARROW_BOTTOM_VAR:()=>xt,SCROLL_ARROW_CLASS:()=>ht,SCROLL_ARROW_LABEL:()=>yt,SCROLL_ARROW_VISIBLE_ATTR:()=>Ve,SKIPPED_PARAM_TEXT:()=>ot,WEEKDAY_LABELS:()=>z,addMonths:()=>ie,attachScrollArrow:()=>$e,buildAttributionUrl:()=>Ne,buildDateOptions:()=>re,buildQuery:()=>E,buildSubmitResult:()=>q,cellDay:()=>oe,cellIso:()=>N,computeOptionsGridLayout:()=>ct,createStore:()=>Ye,cursorIsAtEnd:()=>we,extractPlainText:()=>ee,formatDate:()=>it,getCursorOffset:()=>D,getFooterHint:()=>He,identifiedParamLabel:()=>L,isOptionsGridMobileViewport:()=>Me,isoDate:()=>C,measureOptionsGrid:()=>De,monthLabel:()=>ne,needsOptionsGridMeasurement:()=>Oe,optionEnterDelayMs:()=>We,optionsEntranceDurationMs:()=>Ge,optionsGridTemplateColumns:()=>ut,parseDate:()=>X,parseLooseDate:()=>J,plainTextLength:()=>Pe,planOptionsGrid:()=>Ie,previousGraphemeBoundary:()=>Ee,renderEditableContent:()=>Qe,resolveFormatType:()=>k,resolveIdentifiedDate:()=>ae,scrollCaretIntoView:()=>ye,selectedIsoFromText:()=>V,setCursorOffset:()=>T,withSkippedParams:()=>$});module.exports=Kn(er);function tt(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function L(n){let e=tt(n);return e.length>0?e.join(" "):n}var G=["January","February","March","April","May","June","July","August","September","October","November","December"],z=["S","M","T","W","T","F","S"],Ct=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],At="aiaDate",Ot="aiaDay",Et=n=>String(n).padStart(2,"0");function C(n){return`${n.getFullYear()}-${Et(n.getMonth()+1)}-${Et(n.getDate())}`}function nt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Un(n){let e=nt(n).getTime()-nt(new Date).getTime();return Math.round(e/864e5)}function it(n){let e=Un(n);return e>=0&&e<7?Ct[n.getDay()]:n.getFullYear()===new Date().getFullYear()?`${G[n.getMonth()]} ${n.getDate()}`:`${G[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function X(n){if(!n)return null;let e=Ct.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=nt(new Date),d=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+d)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=G.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let r=Number(t[2]),o=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(o,i,r);return s.getMonth()!==i||s.getDate()!==r?null:s}function ne(n){return`${G[n.month]} ${n.year}`}function rt(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function It(n){return{year:n.getFullYear(),month:n.getMonth()}}function ie(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Tt(){return{text:"",is_tappable:!1,kind:null}}function re(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(Tt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:it(o),is_tappable:!0,kind:null,metadata:{[At]:C(o),[Ot]:r}})}for(;i.length%z.length!==0;)i.push(Tt());return i}function V(n){let e=X(n);return e?C(e):null}function N(n){let e=n?.metadata?.[At];return typeof e=="string"?e:null}function oe(n){let e=n?.metadata?.[Ot];return typeof e=="number"?e:null}function qn(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Dt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:G.findIndex(t=>t.toLowerCase().startsWith(e))}function Qn(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 Mt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function J(n,e={}){if(!n)return null;let t=e.today??new Date,i=qn(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let d=Mt(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=Dt(o[1]);if(d>=0)return se(d,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let d=Dt(s[2]);if(d>=0)return se(d,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let d=Number(a[1]),l=Number(a[2]);return d>12&&l<=12?se(l-1,d,a[3],t):l>12&&d<=12?se(d-1,l,a[3],t):null}return null}function se(n,e,t,i){if(t){if(t.length!==4)return null;let o=Mt(Number(t),n,e);return o?C(o):null}let r=Qn(n,e,i);return r?C(r):null}function ae(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:J(n.text,e)}var Yn=new Set(["date","dates"]),Lt=3;function jn(n){if(!n)return 0;let e=0;for(let t of n)if(t.is_tappable&&(J(t.text)!==null&&(e+=1),e>=Lt))return e;return e}function k(n){if(!n)return"options";let e=n.formatType;return e==="date"||e==="options"?e:tt(n.type).some(t=>Yn.has(t))||jn(n.options)>=Lt?"date":"options"}var le=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 zn="https://api.ai-autocomplete.com",de=`${zn}/api/suggest`,kt=new WeakMap;function Z(n){return n?.type==="accessToken"}function Xn(n){if(!(!n||Z(n)))return n}function ce(n){let e=kt.get(n.getAccessToken);return e||(e=new le(n),kt.set(n.getAccessToken,e)),e}function ue(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function pe(n){let e=Xn(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var ot="skipped";function $(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:ot,kind:null}));return i.length>0?[...n,...i]:n}var Jn="0.16.0",Rt=!1;function Zn(){return crypto.randomUUID()}function ei(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function ti(n,e,t,i,r,o,s,a){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:$(e.map(c=>ei(c,t)),s??[]),...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},...a!==void 0&&{additional_context:a}},meta:{request_id:Zn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Jn,session_id:i}}}async function _t(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Nt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=ti(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=ue(i),a=i?.endpoint??de,d=JSON.stringify(o);if(Z(i)){let u=ce(i),p=await u.getToken(),g=await _t(a,s,p,d,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await _t(a,s,h,d,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=pe(i);!l&&!Rt&&(Rt=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let c=await fetch(a,{method:"POST",headers:s,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=[],s=0;for(let a of e){let d=(i[a.type]??0)+1;i[a.type]=d;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&o.some(x=>h<x.end&&h+a.text.length>x.start);)h=t.indexOf(a.text,h+1);return h},p=u(s);if(p===-1&&(p=u(0)),p!==-1){t=t.slice(0,p)+c+t.slice(p+a.text.length);let g=c.length-a.text.length;for(let h of o)h.start>=p+a.text.length&&(h.start+=g,h.end+=g);o.push({start:p,end:p+c.length}),s=p>=s?p+c.length:s+g}r.push({...a,placeholder:c})}return{rawQuery:t,completedParams:r}}function R(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function me(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function H(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 Ht(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 s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function F(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 K(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 Ft(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 Bt(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 Wt(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 Gt(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 Vt(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 st(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function $t(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);for(;a!==-1&&e.some(d=>a<d.end&&a+s.text.length>d.start);)a=n.indexOf(s.text,a+1);if(a===-1){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function Kt(n,e,t=[]){let i=st(n,e).located,r=$t(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),s=[],a=0;for(let l of o)l.start>a&&s.push({type:"text",value:n.slice(a,l.start)}),s.push(l.segment),a=l.end;let d=n.slice(a);return d&&s.push({type:"text",value:d}),s}function Ut(n,e){let{located:t,missing:i}=st(n,e);return{valid:t.map(r=>r.param),invalid:i}}function fe(n,e,t){let i=st(n,e).located,{located:r,missing:o}=$t(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function ni(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var ii=100,ri=300,oi=2,ge=class{constructor(e,t,i,r,o,s,a,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=s;this.getAdditionalContext=a;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 s=this.store.get(),a=s.pendingSpan?Gt(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,d=await Nt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(b=>b.source==="identified").map(b=>({id:crypto.randomUUID(),type:b.type,text:b.text})),c=Ft(d.data.suggestions??[],this.getOptionOverrides()),u=d.data.input??[],p=u[u.length-1],g=this.store.get().text,h,x;if(p?.state==="in_progress"){x=!0;let b=g.toLowerCase().lastIndexOf(p.text.toLowerCase());h=b!==-1?b:o}else x=!1,h=o;let m=c.filter(b=>b.type!=="placeholder")[0],f=null;if(m&&k(m)!=="date"){let b=H(g,h,x),S=K(m.options,b);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(b=>{let S=f?[...b.completedParams,f]:b.completedParams,P=fe(b.text,S,l).valid,v=new Set(s.skippedParams.map(w=>w.id)),O=new Set(b.skippedParams.filter(w=>!v.has(w.id)).map(w=>w.type));return{suggestions:O.size>0?c.filter(w=>w.type==="placeholder"||!O.has(w.type)):c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:x,identifiedParams:P,...f?{completedParams:S}:{}}})}catch(s){let a=ni(s);r===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}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(b=>b.type==="placeholder").map(b=>b.text).join(" "),s=R(r.text,r.filterBase,o),a=H(r.text,s,r.filterInProgress),l=r.suggestions.filter(b=>b.type!=="placeholder")[0],c=r.activeFormatType==="date",p=(l&&!c?F(l.options,a):[]).filter(b=>b.is_tappable),g=l&&!c?K(l.options,a)!==null:!1,h=a.trim().length>0;if(p.length>0&&!g&&h||me(r.text,r.completedParams.length,o))return!1;let{rawQuery:x,completedParams:y}=E(r.text,r.completedParams),m=x.length<r.lastRawQuery.length,f=Math.abs(x.length-r.lastRawQuery.length);return m||f>=i?(this.doFetch(x,y),!0):!1};this.debounceTimer=setTimeout(()=>{t(oi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ii),this.slowDebounceTimer=setTimeout(()=>t(1),ri)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function si(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function he(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&si(e)?e:n.ownerDocument??n}function A(n){return n.ownerDocument??n}function I(n){let t=he(n).getSelection?.();return t||(A(n).getSelection?.()??null)}function be(n,e){let t=n?he(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var xe=2,ai="magicx-aia";function qt(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function li(n){let e=A(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let r=i.scrollWidth>i.clientWidth,o=i.scrollHeight>i.clientHeight;if(r||o){let s=t.getComputedStyle(i);if(r&&qt(s.overflowX)||o&&qt(s.overflowY))return i}if(i.classList.contains(ai))return null;i=i.parentElement}return null}function ye(n){let e=I(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=li(n);if(!i||typeof t.getBoundingClientRect!="function")return;let r=t.getBoundingClientRect();if(r.height===0)return;let o=i.getBoundingClientRect();if(i.scrollWidth>i.clientWidth){let s=o.left+i.clientLeft,a=s+i.clientWidth;r.right>a?i.scrollLeft+=r.right-a+xe:r.left<s&&(i.scrollLeft-=s-r.left+xe)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+xe:r.top<s&&(i.scrollTop-=s-r.top+xe)}}var Yt='[contenteditable="false"]',U;function di(){if(U!==void 0)return U;let n=globalThis.Intl.Segmenter;if(!n)return U=null,null;try{U=new n(void 0,{granularity:"grapheme"})}catch{U=null}return U??null}function Se(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 ve(n){return A(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Se(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ee(n){let e=ve(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Pe(n){let e=ve(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function D(n){let e=I(n);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(Se(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=jt(r.childNodes[s],n);return o+Qt(r,n)}return t.nodeType!==Node.TEXT_NODE||Se(t,n)?null:Qt(t,n)+i}function jt(n,e){if(n.nodeType===Node.TEXT_NODE)return Se(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+=jt(r,e);return i}function Qt(n,e){let t=ve(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=A(n),i=I(n);if(!i)return;let r=Math.max(0,Math.min(e,Pe(n))),o=ve(n),s=0,a=null,d=0,l=o.nextNode(),c=null;for(;l;){let p=l.data.length;if(r<s+p){a=l,d=r-s;break}if(r===s+p){let g=o.nextNode();g?(a=g,d=0):(a=l,d=p);break}s+=p,c=l,l=o.nextNode()}let u=t.createRange();if(a){let p=a.parentElement?.closest('strong[data-seg="completed"]');p&&p!==n&&n.contains(p)?d===0?u.setStartBefore(p):d===a.data.length?u.setStartAfter(p):u.setStart(a,d):u.setStart(a,d)}else c?u.setStart(c,c.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u),ye(n)}function we(n){let e=D(n);return e==null?!1:e>=Pe(n)}function Ee(n,e){if(e<=0)return 0;let t=di();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 q(n,e,t=[]){let{rawQuery:i,completedParams:r}=E(n,e);return{query:n.trim(),raw_query:i,completed_params:$(r,t)}}function at(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")?we(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?D(n):null}var Te=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(o),a=r(),d=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let l=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=at(e.target,t),u=!!t.editingParam;if(!c&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(l)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!1):d[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(d.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),d.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)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let p=d.indexOf(t.activeDropdownIndex),g=p<d.length-1?p+1:0;this.store.set({activeDropdownIndex:d[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!l)break;let p=at(e.target,t),g=!!t.editingParam;if(!p&&!g)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??d[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(d.length===0)return;this.store.set({activeDropdownIndex:h});break}if(d.length===0)break;if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=d.indexOf(t.activeDropdownIndex),u=c>0?c-1:d.length-1;this.store.set({activeDropdownIndex:d[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),T(u,p);break}at(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%s>0){let c=t.activeDropdownIndex-1;c>=0&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let c=lt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),T(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=lt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let c=lt(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,o):a&&a(q(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(c.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=c.indexOf(t.activeDropdownIndex),p;if(u<0)p=e.shiftKey?c.length-1:0;else{let g=e.shiftKey?-1:1;p=(u+g+c.length)%c.length}this.store.set({activeDropdownIndex:c[p]});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 c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),T(c,u)}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(s=>N(s)===i);if(r>=0)return r;let o=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-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,s)=>o.is_tappable?s:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(e){let t=be(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=be(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;r;){let o=getComputedStyle(r).gridTemplateColumns;if(o&&o!=="none"){let s=o.split(" ").filter(Boolean).length;if(s>0)return s}if(r===t)break;r=r.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,r){let o=be(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Ce=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),s=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 a=[...s,r,...o],d=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Ae=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 s=r.transform(o),a=Array.isArray(s)?s:[],d=r.limit!=null?a.slice(0,r.limit):a;if(t.aborted||!i())return;this.commit(d)}catch(o){if(t.aborted||ci(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 ci(n){return n instanceof Error&&n.name==="AbortError"}var te="(max-width: 768px)";var ui="var(--aia-option-row-height, 37px)",pi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ct(n,e){return e?dt(1,Math.min(n,5)):dt(1,Math.min(n,4))}function dt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${ui} + ${pi})`}}function Oe(n,e){return!e&&n>=5}function Ie(n,e,t,i){if(!(!e&&n>=5&&mi(t,i))){let d=ct(n,e);return{...d,template:ut(d.cols),scrollHintIndices:!e&&n>d.rows?[d.rows-1]:[]}}let[o,s]=zt(t),a=6;return{...dt(2,3),template:`minmax(0,${o}fr) minmax(0,${s}fr)`,scrollHintIndices:n>a?[a-2,a-1]:[]}}function zt(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 mi(n,e){if(!n||n.length===0||e==null||e<=0||n.some(r=>r<=0))return!1;let[t,i]=zt(n);return t+i<=e}function De(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let 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 ut(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Me(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(te).matches}function Xt(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,d=n.text.replace(/\s+$/,"").length,l=n.caretOffset==null||n.caretOffset>=d;return(s||n.isLoading)&&a&&l}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function pt(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 fi(n){if(!n)return rt();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function gi(n){let e=X(n);return e?It(e):rt()}function Jt(n,e){let t=Kt(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,s=n.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),a=R(n.text,Math.min(n.filterBase,n.text.length),s),l=a===0&&me(n.text,n.completedParams.length,s)?"":H(n.text,a,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,O=n.completedParams.some(j=>j.id===v),W=n.caretOffset??n.editingAnchor,w=O?"":n.text.slice(n.editingAnchor,W);p=F(n.editingParam.options,w)}else p=F(c,l);let g=e.showNonTappableOptions===!1;g&&(p=p.filter(v=>v.is_tappable));let h=n.editingIdentified,x=h?{type:h.type}:u?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,y=k(x),m=null;if(y==="date"){let v=pt({...n,actionableSuggestions:i}),O=n.dateViewMonth;m=O&&O.key===v?{year:O.year,month:O.month}:h?fi(h.iso):gi(n.editingParam?.text),p=re(m)}let f=v=>g?v.is_tappable:!0,b;if(u){let v=n.editingParam?.options??[];b=n.editingParam!=null&&v.filter(f).length===0}else{let v=r?o?o("")??r.options??[]:r.options??[]:[];b=r!=null&&v.filter(f).length===0}let S=Xt({inEditMode:u||h!=null,filteredOptionsLength:p.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:b,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:y,dateView:m,placeholderText:s,isDropdownOpen:S,isActivePillSelected:P}}function Le(n){return n.mode==="fresh"?hi(n):bi(n)}function hi(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let d=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=R(e,r,d),c=H(e,l,o),u=K(a.options,c);if(!u)return null;let p=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(p),h=g>=0?g:Math.max(0,e.length-u.text.length),x=h+u.text.length,y=e.slice(h,x),f=x<e.length&&e[x]===" "?x+1:x,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:y,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(S=>S!==a),filterBase:f,newParamId:b.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function bi(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(b=>b.id===i.id))return null;let s=e.slice(r,o),a=K(i.options,s);if(!a)return null;let d=a.text.toLowerCase(),l=s.toLowerCase().lastIndexOf(d),c=r+Math.max(0,l),u=c+a.text.length,p=e.slice(c,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,x={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:p,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},y=t.length,m=0;for(let b=0;b<t.length;b++){let S=e.indexOf(t[b].text,m);if(S!==-1){if(S>=g){y=b;break}m=S+t[b].text.length}}let f=[...t];return f.splice(y,0,x),{patch:{text:e,completedParams:f,newParamId:x.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function ke(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 Re=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.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:s}=e===""?ke(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},a=r+e.length;return this.deps.store.set(d=>({text:s,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),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 s=t.text.slice(0,r),a=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${d} `:d,u=s+c+a,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},h=t.completedParams.findIndex(m=>m.id===i.id),x=t.completedParams.filter(m=>m.id!==i.id),y=h>=0?Math.min(h,x.length):x.length;x.splice(y,0,g),this.deps.store.set({text:u,completedParams:x,newParamId:g.id,filterBase: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=Le({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 en=33,tn=70,nn=120,rn=50,B="data-aia-placeholder-leaving",Q=new WeakMap;function _e(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function xi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function on(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function sn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(on(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(()=>sn(n,e),33+i)}function Zt(n,e){on(n,e,0),e.timer=setTimeout(()=>sn(n,e),33)}function an(n,e){let t=Q.get(n);if(e===""){t&&(_e(t),Q.delete(n)),n.removeAttribute(B),delete n.dataset.placeholder;return}if(t?.target===e)return;if(xi(n)){t&&_e(t),n.removeAttribute(B),Q.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&&_e(t),Q.set(n,i),r){n.setAttribute(B,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(B),n.isConnected&&Zt(n,i)},170);return}n.removeAttribute(B),Zt(n,i)}function ln(n){let e=Q.get(n);e&&(_e(e),Q.delete(n))}var mt="https://ai-autocomplete.com";function Ne(n=mt){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 He(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var dn="data-aia-key";function _(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(dn);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],d=t.keyOf(a,s);r.add(d);let l=i.get(d);l||(l=t.create(a,s),l.setAttribute(dn,d)),t.update?.(l,a,s),n.children[s]!==l&&n.insertBefore(l,n.children[s]??null),o.push(l)}for(let[s,a]of i)r.has(s)||a.remove();return o}function un(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=vi(),n.appendChild(a));let d=a.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=ne(r));let l=a.querySelector("[data-aia-date-prev]"),c=a.querySelector("[data-aia-date-next]");l&&(l.onclick=()=>s.onPreviousMonth()),c&&(c.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&yi(u,e,t,i,o,s)}function yi(n,e,t,i,r,o){let s=C(new Date);_(n,e,{keyOf:(a,d)=>N(a)??`pad-${d}`,create:a=>Si(a),update:(a,d,l)=>{let c=N(d),u=l===t&&d.is_tappable;a.id=`${i}-option-${l}`,a.dataset.aiaIndex=String(l),a.setAttribute("aria-selected",String(u)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<s),a.classList.toggle("magicx-aia-date-cell--highlighted",u),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===s),a.classList.toggle("magicx-aia-date-cell--selected",c!=null&&r!=null&&c===r),d.is_tappable?(a.onclick=()=>{a.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(d),setTimeout(()=>a.classList.remove("magicx-aia-date-cell--pressed"),500)},a.onmouseenter=()=>{let p=Number.parseInt(a.dataset.aiaIndex??"-1",10);p>=0&&o.onHighlight(p)}):(a.onclick=null,a.onmouseenter=null)}})}function Si(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=oe(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 vi(){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(cn("prev","Previous month","\u2039"),t,cn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of z){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=o,i.appendChild(s)}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 cn(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 pn=[125,69];function mn(n,e){return e?1:n===0?.7:n===1?.4:.2}function Fe(n,e,t,i,r=!1,o=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let d=0;d<pn.length;d++){let l=pn[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(mn(d,!1)),a.appendChild(c)}return}o?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let d of a.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();_(a,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=s&&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(mn(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 ft(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Pi="Products";function fn(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 a=document.createElement("div");a.className="magicx-aia-products-label",a.id=`${t}-products-label`,a.textContent=Pi;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(a,d),n.appendChild(o)}let s=o.querySelector(".magicx-aia-products-row");s&&_(s,e,{keyOf:a=>wi(a),create:a=>Ei(a,i,r),update:(a,d,l)=>{a.id=`${t}-product-${l}`,a.dataset.aiaIndex=String(l)}})}function gt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function wi(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Ei(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 a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",r.appendChild(a)}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 a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,o.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,o.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,o.appendChild(a)}return i.appendChild(o),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var gn=80,hn=150,bn=280,xn=16,Be="--aia-option-enter-delay";function We(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 s=Math.max(1,Math.ceil(Math.max(0,t)/r));return Math.max(0,s-1-o)*80}function Ge(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 Ti(n,e,t){let i=Me(),r=!t&&Oe(e,i)?De(n):null,o=Ie(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((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&o.scrollHintIndices.includes(a))}),o.cols}function yn(n,e,t,i,r,o,s,a="",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!==a;l.dataset.aiaGroup=a,Ci(l,e,t,i,r,o,s);let u=Ti(l,e.length,s);Ai(l,e.length,u,s,d),c&&(l.scrollTop=0)}function Ci(n,e,t,i,r,o,s){let a=s?"1":"0",d=n.dataset.aiaGroup??"";_(n,e,{keyOf:l=>`${l.text}\0${a}\0${d}`,create:(l,c)=>{let u=Oi(l,s);return s||(u.dataset.aiaEntering=""),u},update:(l,c,u)=>{let p=u===t&&!s;l.id=`${o}-option-${u}`,l.dataset.aiaIndex=String(u),l.setAttribute("aria-selected",String(p)),l.classList.toggle("magicx-aia-option--highlighted",p),!s&&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 Ai(n,e,t,i,r){for(let o of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(o.dataset.aiaIndex??"-1",10);s>=0&&o.style.setProperty(Be,`${We(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function Oi(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 s=document.createElement("span");s.className="magicx-aia-option-tag",s.textContent=n.tag,r.appendChild(s)}return t.appendChild(r),t}var ht="magicx-aia-scroll-arrow",bt="data-aia-scroll-arrow",Ve="data-aia-visible",xt="--aia-scroll-arrow-bottom",yt="Scroll down for more options",Ii=4,Di=8,Mi=240;function Li(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||vn(n)){n.scrollTop=r+e,i();return}let a=t.performance?.now?.()??Date.now(),d=()=>t.performance?.now?.()??Date.now(),l=()=>{let c=Math.min(1,(d()-a)/Mi),u=1-(1-c)*(1-c);n.scrollTop=r+e*u,c<1?o.call(t,l):i()};o.call(t,l)}function ki(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 Sn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=ht,e.setAttribute(bt,""),e.setAttribute("aria-label",yt),e.setAttribute("aria-hidden","true"),e.appendChild(ki(n)),e}function Ri(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function vn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function $e({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),r=!1,o=null,s=null,a=x=>{x?(t.setAttribute(Ve,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(Ve),t.setAttribute("aria-hidden","true"))},d=()=>{let x=0,y=e;for(;y&&y!==n;)x+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;let m=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0,f=n.clientHeight-(x+e.offsetHeight)+(m>0?0:Di);t.style.setProperty(xt,`${Math.max(0,Math.round(f))}px`)},l=()=>{if(r||s!==null)return;let x=e.querySelector("[data-aia-option][data-aia-loading]")!==null,y=e.scrollHeight-e.clientHeight-e.scrollTop;a(!x&&y>Ii)},c=()=>{if(r)return;d();let x=e.getAttribute("data-aia-group")??"";if(x!==o){o=x,a(!1),s!==null&&clearTimeout(s);let y=e.querySelectorAll("[data-aia-option]").length,m=vn(e)?0:Ge(y,Ri(e));s=setTimeout(()=>{s=null,l()},m);return}l()},u=()=>l();e.addEventListener("scroll",u,{passive:!0});let p=x=>x.preventDefault(),g=()=>{let x=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,y=Math.max(1,e.clientHeight-x);Li(e,y,i,l)};t.addEventListener("mousedown",p),t.addEventListener("click",g);let h=null;return i&&typeof i.ResizeObserver=="function"&&(h=new i.ResizeObserver(()=>{d(),l()}),h.observe(e)),c(),{update:c,destroy(){r||(r=!0,s!==null&&clearTimeout(s),s=null,e.removeEventListener("scroll",u),t.removeEventListener("mousedown",p),t.removeEventListener("click",g),h?.disconnect(),a(!1))}}}var _i=[159,119,164];function Ue(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 Ke=new WeakMap;function Ni(n,e){let t=Ke.get(n);if(t||(t={button:Sn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Ke.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=$e({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function St(n){let e=Ke.get(n);e&&(e.controller?.destroy(),Ke.delete(n))}function qe(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:u,onSkip:p}=e,g=s.length>0,h=a&&g,x=t.length>0,y=e.products.length>0,m=r&&(x||h||o||y);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){gt(n,!1);return}y?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 b=e.showSkipButton&&g&&!e.isInputEmpty,S=h||o&&a||b,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 M=P.querySelector(".magicx-aia-pill-scroll");M||(M=document.createElement("span"),M.className="magicx-aia-pill-scroll",M.setAttribute("data-aia-pill-scroll",""),P.insertBefore(M,P.firstChild)),Fe(M,a?s:[],0,u,!0,o&&a,d),Fi(P,b,o||e.skipDisabled,s[0],p)}else P&&P.remove();let v=e.suggestions[0],O=v?`${v.type} ${v.text}`:"",W=e.formatType==="date";yn(f,W?[]:t,i,l,c,e.listboxId,o,O,e.optionsPosition??"below"),Ni(n,f.querySelector(".aia-grid")),un(f,W?t:[],i,e.listboxId,W?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&&!x){if(!w){w=document.createElement("div"),w.className="magicx-aia-skeleton-bars",w.setAttribute("data-aia-skeleton-bars","");for(let M of _i){let Ze=document.createElement("span");Ze.className="magicx-aia-skeleton-bar",Ze.style.width=`${M}px`,w.appendChild(Ze)}f.appendChild(w)}}else w&&w.remove();fn(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),gt(n,!0);let j=f.querySelector(".magicx-aia-footer")??Wi(),Fn=i>=0&&!!t[i]?.is_tappable;Bi(j,He(Fn,e.isInputEmpty)),j.isConnected||f.appendChild(j),Hi(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Hi(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 Fi(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",s=>s.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Bi(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 Wi(){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=Ne(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",o.append(s,a),e.append(t,o),n.append(e),n}function Pn(n,e){let t=Ue(e.listboxId);return n.appendChild(t),{dropdown:t}}function vt(n,e,t){qe(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:L(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:V(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 Gi=6,Vi=.3;function wn(n){return n<=0?"0px":`${(-Math.min(Vi,2*Gi/n)).toFixed(3)}px`}function Qe(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",an(e,a?o:"");let d=t.map(y=>`${y.type}:${y.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=s?D(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let g=A(e),h=g.createDocumentFragment(),x=0;for(let y of t)if(x+=y.value.length,y.type==="completed"){let m=g.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=y.param.id;let f=y.param.id===i,b=y.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];f&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),b&&S.push("magicx-aia-segment--editing"),m.className=S.join(" "),m.style.letterSpacing=wn(y.value.length),m.textContent=y.value,h.appendChild(m)}else if(y.type==="identified"){let m=g.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=y.param.id;let f=["magicx-aia-segment","magicx-aia-segment--completed"];y.param.id===r&&f.push("magicx-aia-segment--editing"),m.className=f.join(" "),m.style.letterSpacing=wn(y.value.length),m.textContent=y.value,h.appendChild(m)}else h.appendChild(g.createTextNode(y.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(x),p!=null&&T(e,Math.max(0,Math.min(p,x)))}var $i='<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 En(){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=$i,n}function Ki(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Tn(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 Cn(n,e){let{listboxId:t}=e,i=Ue(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 s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",Ki()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let d=null,l=null;e.submitButton===void 0?(d=En(),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,h=()=>{let m=ee(s),b=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(b)},x=()=>{let m=I(s);if(!m||m.rangeCount===0)return null;let f=m.anchorNode;return!f||!s.contains(f)?null:(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null};if(r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{p||(g=performance.now(),h(),e.handleCaretAfterInput(D(s)))},{signal:u}),A(s).addEventListener("selectionchange",()=>{let m=I(s);if(!m||m.rangeCount===0||!s.contains(m.anchorNode))return;let f=m.isCollapsed?x():null,b=e.store.get(),S=b.editingParam?.id??b.editingIdentified?.id??null;if(f&&f!==S){e.startEditingParam(f);return}performance.now()-g<50||e.handleCaretMove(D(s))},{signal:u}),s.addEventListener("compositionstart",()=>{p=!0},{signal:u}),s.addEventListener("compositionend",()=>{p=!1,h()},{signal:u}),s.addEventListener("beforeinput",m=>{let f=m,b=f.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){m.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let S=b.startsWith("delete")?"":f.data??"";e.replaceEditingRange(S)&&m.preventDefault()}},{signal:u}),s.addEventListener("paste",m=>{m.preventDefault();let f=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let b=A(s),S=I(s);if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!s.contains(P.startContainer))return;P.deleteContents();let v=b.createTextNode(f);P.insertNode(v),P.setStartAfter(v),P.collapse(!0),S.removeAllRanges(),S.addRange(P),h()},{signal:u}),s.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.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(q(f.text,f.completedParams,f.skippedParams))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let m=A(s),f=I(s),b=f&&f.rangeCount>0&&s.contains(f.anchorNode);if(f&&!b){let S=m.createRange();S.selectNodeContents(s),S.collapse(!0),f.removeAllRanges(),f.addRange(S)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Tn(s,a));m.observe(s),c.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:d,abort:c}}function Pt(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,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"),s){let y=!!e.text||e.completedParams.length>0;s.disabled=!y}let p=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==p;if(Qe({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let y=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;y||e.actionableSuggestions.length>0?Fe(r,e.actionableSuggestions,0,d,!1,y,e.isActivePillSelected):ft(r)}else ft(r);Tn(i,r),g?(i.focus(),T(i,e.caretOffset??e.text.length)):e.isFocused&&ee(i)!==e.text&&T(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:L(e.editingIdentified.type),required:!0,options:[]}:null,x=h??e.actionableSuggestions[0];qe(o,{suggestions:x?[{...x,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="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:V(e.editingParam?.text),optionsPosition:t.optionsPosition??"below",onSelect:l,onHighlight:y=>c.set({activeDropdownIndex:y}),onPillClick:d,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:y=>c.set({isFocused:y})})}function An(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,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=Ht(r,e.text);a>0&&(r=r.slice(0,r.length-a));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,c=(o||s)&&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},h=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(x=>x.text!==e.text).map(x=>x.text)},consumedSuggestion:t,remainingActionable:h}}function Ye(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!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 On(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(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let d={...a,...r(a)},l={...s,...r(s)};o(l,d)})}}var wt=new WeakSet,In=new WeakMap;function Mn(n){return n.nodeType===Node.DOCUMENT_NODE}function Ui(n){return Mn(n)?n:n.ownerDocument}function qi(n){let e=In.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(kn),In.set(n,i),i)}catch{return null}}function Dn(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=kn,e.appendChild(t)}function Ln(n){if(typeof document>"u")return;let e=n??document;if(wt.has(e))return;let t=Ui(e);if(Mn(e)){let o=e.head??e.documentElement;if(!o)return;Dn(t,o),wt.add(e);return}let i=qi(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):Dn(t,e),wt.add(e)}var kn=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -1584,5 +1584,5 @@
1584
1584
  background: var(--aia-surface, #ffffff);
1585
1585
  }
1586
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});
1587
+ `;var je=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 ze=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=(...s)=>t(...s);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 Xe=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 Y=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 Qi(n){return(n??de).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Yi(n){return Z(n)?`Bearer ${await ce(n).getToken()}`:pe(n)}async function Rn(n){try{let e=Qi(n.apiConfig?.endpoint),t=ue(n.apiConfig),i=await Yi(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 ji="newParam",_n="suggestionRemoval",zi="selectionAnimation",Xi=650,Ji=0;function Zi(){return`:ac-${++Ji}:`}var Nn=500;function Hn(){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 Je=class{constructor(e,t={}){this.inputStore=Ye(Hn());this._listboxId=Zi();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Xe;this.boundary=new je;this.subscriberCount=0;this.emitter=new ze(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=On(this.inputStore,i=>Jt(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 Ce(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Re({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Ae(this.store,()=>this.opts.products),this.fetchController=new ge(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(s=>s.text!==r.text).map(s=>s.text)})}}),this.keyboardController=new Te(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:s}=fe(i.text,i.completedParams,i.identifiedParams);s.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 s=0,a;for(let d of i.segments){if(d.type==="identified"&&s===o.anchor&&d.value===o.text){a=d.param;break}s+=d.value.length}if(a){this.store.set({editingIdentified:{...o,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let s=o.anchor;if(i.text!==r.text){let d=Vt(r.text,i.text,s);if(d===null){this.store.set({pendingSpan:null});return}s=d}i.text.slice(s).trim().length===0||Wt(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(Ln(this.opts.styleRoot??he(this.container)),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({...Hn(),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&&(ln(this.domRefs.input),St(this.domRefs.dropdown)),this.dropdownRefs&&St(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}=ke(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 s=Ee(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(d=>({text:a,filterBase:Math.min(d.filterBase,a.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),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(a=>a.id===e);if(!i||k(i)!=="date")return!1;let r=0,o=-1;for(let a of t.segments){if(a.type!=="text"&&a.param.id===e){o=r;break}r+=a.value.length}if(o<0)return!1;let s=o+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:o,tail:s,text:i.text,iso:ae(i)},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:s,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=ie(t.dateView,e);this.store.set({dateViewMonth:{...i,key:pt(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{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=An(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(_n),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(_n,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},Nn)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(zi,()=>this.store.set({inSelectionAnimation:!1}),Nn)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Rn({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 Y(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=Cn(this.container,t);let i=()=>{this.domRefs&&Pt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Pt(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=Pn(this.container,t);let i=()=>{this.dropdownRefs&&vt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),vt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(te),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(ji,()=>this.store.set({newParamId:null}),Xi)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Ut(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=R(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Bt(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);F(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),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=o.length===0||o[0]!==" "?`${s} `:s,l=r+d+o,c=l.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:L(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=Le({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});
1588
1588
  //# sourceMappingURL=index.js.map