import{g as m,s as g,a as b,b as w}from"../frontend.js";import"./preload-helper-Du-ZIQLl.js";const y=window.FindAstraConfig||{},l=y.i18n||{},v=(i,t)=>{let e;return(...s)=>{clearTimeout(e),e=setTimeout(()=>i(...s),t)}};class _{constructor(t){this.input=t,this.form=t.closest("form"),this.isServerSide=m(),this.results=[],this.fallback=[],this.selectedIdx=-1,this.lastQuery="",this.requestId=0,this.panel=this.buildPanel(),this.open=!1,t.setAttribute("autocomplete","off"),t.dataset.findastraAttached="1",t.addEventListener("input",v(()=>this.handleInput(),180)),t.addEventListener("keydown",e=>this.handleKeydown(e)),t.addEventListener("focus",()=>{t.value.trim().length>=2&&this.results.length>0&&this.show()}),t.addEventListener("blur",()=>{setTimeout(()=>{this.panel.matches(":hover")||this.hide()},150)}),this.form&&this.form.addEventListener("submit",e=>this.handleSubmit(e)),document.addEventListener("click",e=>{!this.panel.contains(e.target)&&e.target!==t&&this.hide()}),window.addEventListener("resize",()=>this.reposition()),window.addEventListener("scroll",()=>this.reposition(),{passive:!0})}buildPanel(){const t=document.createElement("div");return t.className="findastra-autocomplete",t.setAttribute("role","listbox"),t.dataset.findastraAc="1",t.style.display="none",document.body.appendChild(t),t}reposition(){if(!this.open)return;const t=this.input.getBoundingClientRect(),e=t.bottom+window.scrollY+6,s=t.left+window.scrollX,a=Math.max(280,t.width);this.panel.style.top=`${e}px`,this.panel.style.left=`${s}px`,this.panel.style.width=`${a}px`}show(){this.panel.style.display="block",this.open=!0,this.reposition()}hide(){this.panel.style.display="none",this.open=!1,this.selectedIdx=-1}async handleInput(){const t=this.input.value.trim();if(t.length<2){this.results=[],this.fallback=[],this.hide();return}if(t===this.lastQuery)return;this.lastQuery=t;const e=++this.requestId;this.renderLoading(),this.show();try{const s=await g(t,6);if(e!==this.requestId)return;this.results=s.results||[],this.fallback=s.fallback||[],this.selectedIdx=-1,this.render()}catch(s){if(e!==this.requestId)return;console.error("[FindAstra]",s),this.renderError()}}handleKeydown(t){const e=this.visibleItems().length;if(!this.open||e===0){t.key==="Escape"&&this.hide();return}if(t.key==="ArrowDown")t.preventDefault(),this.selectedIdx=(this.selectedIdx+1)%e,this.updateSelection();else if(t.key==="ArrowUp")t.preventDefault(),this.selectedIdx=(this.selectedIdx-1+e)%e,this.updateSelection();else if(t.key==="Enter"){if(this.selectedIdx>=0){t.preventDefault();const s=this.visibleItems()[this.selectedIdx];s&&s.permalink&&(window.location.href=s.permalink)}}else t.key==="Escape"&&this.hide()}async handleSubmit(t){if(this.isServerSide)return;const e=(this.input.value||"").trim();if(e.length<2)return;t.preventDefault();let s;if(e===this.lastQuery&&this.results.length>0)s=this.results;else try{const r=await b(e,24,{log:!1});s=r.results&&r.results.length?r.results:r.fallback||[]}catch(r){console.warn("[FindAstra] submit-time search failed:",r),s=[]}const a=s.map(r=>r.product_id).filter(Boolean);let n=null;a.length&&(n=await w(a));const u=this.form.getAttribute("action")||window.location.origin,o=new URL(u,window.location.href),p=this.input.getAttribute("name")||"s";o.searchParams.set(p,e),o.searchParams.has("post_type")||o.searchParams.set("post_type","product"),n&&o.searchParams.set("ss",n),window.location.href=o.toString()}visibleItems(){return this.results.length>0?this.results:this.fallback}updateSelection(){this.panel.querySelectorAll(".findastra-autocomplete__item").forEach((e,s)=>{e.classList.toggle("is-active",s===this.selectedIdx),s===this.selectedIdx&&e.scrollIntoView({block:"nearest"})})}renderLoading(){this.panel.innerHTML=`<div class="findastra-autocomplete__hint">${this.escape(l.searching||"Searching…")}</div>`}renderError(){this.panel.innerHTML=`<div class="findastra-autocomplete__hint">${this.escape(l.error||"Search failed.")}</div>`}render(){const t=this.visibleItems();if(t.length===0){this.panel.innerHTML=`<div class="findastra-autocomplete__hint">${this.escape(l.no_results||"No matching products.")}</div>`;return}const e=this.results.length===0;let s="";e&&(s+=`<div class="findastra-autocomplete__hint">${this.escape(l.no_results_fallback||"No exact matches — popular picks:")}</div>`);for(let a=0;a<t.length;a++){const n=t[a];s+=`
				<a
					class="findastra-autocomplete__item${e?" is-fallback":""}"
					role="option"
					data-idx="${a}"
					href="${this.escape(n.permalink)}"
				>
					${n.image?`<img class="findastra-autocomplete__image" src="${this.escape(n.image)}" alt="" loading="lazy" />`:""}
					<span class="findastra-autocomplete__meta">
						<span class="findastra-autocomplete__title">${this.escape(n.title)}</span>
						<span class="findastra-autocomplete__price">${n.price_html||""}</span>
					</span>
				</a>
			`}this.panel.innerHTML=s,this.panel.querySelectorAll(".findastra-autocomplete__item").forEach(a=>{a.addEventListener("mousedown",n=>{n.preventDefault()}),a.addEventListener("mouseover",()=>{this.selectedIdx=parseInt(a.dataset.idx,10),this.updateSelection()})})}escape(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}}const d=window.FindAstraConfig||{},E=!(d.theme&&d.theme.autocomplete===!1),I=['input[type="search"]:not([data-findastra-attached])','input[name="s"]:not([data-findastra-attached])','input[type="text"][placeholder*="search" i]:not([data-findastra-attached])','input[type="text"][placeholder*="find" i]:not([data-findastra-attached])'],S=['form[role="search"]',"form.search-form","form.searchform","form.wp-block-search__form",".wp-block-search"];function k(i){return!(!(i instanceof HTMLInputElement)||i.dataset.findastraAttached==="1"||i.closest("[data-findastra-widget]")||i.closest("#wpadminbar")||i.dataset.findastraSkip==="1"||i.type==="hidden")}function c(i){if(!k(i))return!1;try{return new _(i),!0}catch(t){return console.warn("[FindAstra] failed to attach autocomplete:",t),!1}}function h(i=document){let t=0;for(const e of I)i.querySelectorAll(e).forEach(s=>{c(s)&&t++});for(const e of S)i.querySelectorAll(e).forEach(s=>{s.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"])').forEach(n=>{c(n)&&t++})});return t}function f(){if(!E)return;h(document),new MutationObserver(t=>{for(const e of t)for(const s of e.addedNodes)s instanceof Element&&(s.matches&&s.matches("input")?c(s):h(s))}).observe(document.body,{childList:!0,subtree:!0})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",f):f();
//# sourceMappingURL=theme-integration-CgzpZgJ4.js.map
