@seekora-ai/ui-sdk-vanilla 0.2.23 → 0.2.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.umd.js +1 -1
- package/package.json +3 -3
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SeekoraVanilla={})}(this,function(e){"use strict";const t={small:14,medium:18,large:24},n={small:"0.75rem",medium:"0.875rem",large:"1rem"};class s{constructor(e,t){if(this.hoverRating=null,this.container="string"==typeof e?document.querySelector(e):e,!this.container)throw new Error("RatingDisplay: Container element not found");this.options={variant:"compact",size:"medium",maxRating:5,showNumeric:!1,showHalfStars:!0,interactive:!1,starColor:"#f59e0b",emptyStarColor:"#d1d5db",textColor:"var(--seekora-text-secondary, #6b7280)",showReviewCount:!0,onRatingChange:()=>{},reviewCountFormat:this.defaultReviewCountFormat,className:"",...t},this.render()}defaultReviewCountFormat(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString()}createStarSVG(e,t,n){const{starColor:s,emptyStarColor:i}=this.options;return t?`\n <svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <defs>\n <linearGradient id="half-fill-${Math.random()}">\n <stop offset="50%" stop-color="${s}" />\n <stop offset="50%" stop-color="${i}" />\n </linearGradient>\n </defs>\n <path\n d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"\n fill="url(#half-fill-${Math.random()})"\n stroke="${s}"\n stroke-width="1"\n />\n </svg>\n `:`\n <svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="${e?s:"none"}" xmlns="http://www.w3.org/2000/svg">\n <path\n d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"\n stroke="${e?s:i}"\n stroke-width="1.5"\n stroke-linecap="round"\n stroke-linejoin="round"\n />\n </svg>\n `}renderStars(){const{rating:e,maxRating:n,showHalfStars:s,interactive:i}=this.options,r=i&&null!==this.hoverRating?this.hoverRating:e,o=t[this.options.size];let a="";for(let e=1;e<=n;e++){const t=e<=Math.floor(r),n=s&&e===Math.ceil(r)&&r%1>=.25&&r%1<.75;a+=`\n <span\n class="${`seekora-rating-star ${t?"seekora-rating-star--filled":"seekora-rating-star--empty"} ${i?"seekora-rating-star--interactive":""}`}"\n data-rating="${e}"\n style="display: inline-block; width: ${o}px; height: ${o}px; cursor: ${i?"pointer":"default"};"\n >\n ${this.createStarSVG(t,n,o)}\n </span>\n `}return`<div style="display: inline-flex; align-items: center; gap: 2px;">${a}</div>`}render(){const{variant:e,rating:t,reviewCount:s,showNumeric:i,showReviewCount:r,textColor:o,maxRating:a,className:l}=this.options,h=n[this.options.size],c=Math.max(0,Math.min(a,t));let d="";"stars-only"===e?d=`\n <div class="seekora-rating-display seekora-rating-display--stars-only ${l}"\n style="display: inline-flex; align-items: center; gap: 2px;">\n ${this.renderStars()}\n </div>\n `:"compact"===e?d=`\n <div class="seekora-rating-display seekora-rating-display--compact ${l}"\n style="display: inline-flex; align-items: center; gap: 4px; font-size: ${h};">\n ${this.renderStars()}\n ${i?`<span class="seekora-rating-numeric" style="font-weight: 600; color: ${o};">${c.toFixed(1)}</span>`:""}\n ${r&&null!=s&&s>0?`<span class="seekora-rating-review-count" style="color: ${o};">(${this.options.reviewCountFormat(s)})</span>`:""}\n </div>\n `:"inline"===e?d=`\n <div class="seekora-rating-display seekora-rating-display--inline ${l}"\n style="display: inline-flex; align-items: center; gap: 6px; font-size: ${h};">\n <span class="seekora-rating-numeric" style="font-weight: 600; color: var(--seekora-text-primary, #111827);">${c.toFixed(1)}</span>\n ${this.renderStars()}\n ${r&&null!=s&&s>0?`<span class="seekora-rating-review-count" style="color: ${o};">(${this.options.reviewCountFormat(s)})</span>`:""}\n </div>\n `:"full"===e&&(d=`\n <div class="seekora-rating-display seekora-rating-display--full ${l}"\n style="display: flex; flex-direction: column; gap: 4px; font-size: ${h};">\n <div style="display: flex; align-items: center; gap: 6px;">\n ${this.renderStars()}\n <span class="seekora-rating-numeric" style="font-weight: 600; color: var(--seekora-text-primary, #111827);">${c.toFixed(1)}</span>\n <span class="seekora-rating-max" style="color: ${o};">/ ${a}</span>\n </div>\n ${r&&null!=s&&s>0?`\n <span class="seekora-rating-review-text" style="font-size: 0.875em; color: ${o};">\n Based on ${this.options.reviewCountFormat(s)} ${1===s?"review":"reviews"}\n </span>\n `:""}\n </div>\n `),this.container.innerHTML=d,this.options.interactive&&this.attachEventListeners()}attachEventListeners(){this.container.querySelectorAll(".seekora-rating-star").forEach(e=>{e.addEventListener("mouseenter",()=>{const t=parseInt(e.dataset.rating||"0");this.hoverRating=t,this.render()}),e.addEventListener("click",()=>{const t=parseInt(e.dataset.rating||"0");this.hoverRating=null,this.options.onRatingChange(t),this.render()})}),this.container.addEventListener("mouseleave",()=>{this.hoverRating=null,this.render()})}update(e){this.options={...this.options,...e},this.render()}destroy(){this.container.innerHTML=""}}const i=(e,t="₹")=>{if(null!=e){if("number"==typeof e)return`${t}${e}`;if("string"==typeof e){const n=parseFloat(e);return isNaN(n)?e:`${t}${n}`}return String(e)}},r=(e,t)=>{if(t)return((e,t)=>{if(t)return t.split(".").reduce((e,t)=>e?.[t],e)})(e,t)};var o;!function(e){e[e.VERBOSE=0]="VERBOSE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT"}(o||(o={}));class a{constructor(e={}){this.level=e.level??this.getDefaultLevel(),this.prefix=e.prefix??"[Seekora UI SDK]",this.enableTimestamp=e.enableTimestamp??!1}getDefaultLevel(){switch(void 0){case"VERBOSE":return o.VERBOSE;case"INFO":return o.INFO;case"WARN":return o.WARN;case"ERROR":return o.ERROR;case"SILENT":return o.SILENT}return"undefined"!=typeof window&&window.__SEEKORA_DEBUG__?o.VERBOSE:o.INFO}formatMessage(e,...t){const n=[];return this.enableTimestamp&&n.push(`[${(new Date).toISOString()}]`),n.push(this.prefix,`[${e}]`),[...n,...t]}verbose(...e){this.level<=o.VERBOSE&&console.log(...this.formatMessage("VERBOSE",...e))}info(...e){this.level<=o.INFO&&console.info(...this.formatMessage("INFO",...e))}warn(...e){this.level<=o.WARN&&console.warn(...this.formatMessage("WARN",...e))}error(...e){this.level<=o.ERROR&&console.error(...this.formatMessage("ERROR",...e))}setLevel(e){this.level=e}getLevel(){return this.level}setPrefix(e){this.prefix=e}setTimestamp(e){this.enableTimestamp=e}}let l=null;function h(){return l||(l=function(e={}){return new a(e)}()),l}const c=(...e)=>h().verbose(...e),d=(...e)=>h().info(...e),u=(...e)=>h().warn(...e),g=(...e)=>h().error(...e);function p(e){const{attribute:t,hit:n,preTag:s="<mark>",postTag:i="</mark>",fallback:r}=e,o=n._highlightResult?.[t]?.value||n.highlight_result?.[t]?.value||n._highlight?.[t]||n.highlight?.[t];if(o)return o.replace(/<em>/g,s).replace(/<\/em>/g,i).replace(/<mark>/g,s).replace(/<\/mark>/g,i);const a=(l=n,t.split(".").reduce((e,t)=>e&&void 0!==e[t]?e[t]:void 0,l));var l;return void 0!==a?String(a):r||""}h();class m{constructor(e){this.listeners=[],this.debounceTimer=null,this.client=e.client,this.autoSearch=!1!==e.autoSearch,this.debounceMs=e.debounceMs||300,this.defaultSearchOptions=e.defaultSearchOptions||{widget_mode:!0},this.keepResultsOnClear=!1!==e.keepResultsOnClear,this.abTestId=e.abTestId,this.abVariant=e.abVariant,this.state={query:e.initialQuery||"",refinements:[],currentPage:1,itemsPerPage:e.itemsPerPage||10,sortBy:void 0,results:null,loading:!1,error:null},d("SearchStateManager: Initialized",{autoSearch:this.autoSearch,debounceMs:this.debounceMs})}getState(){return{...this.state}}getQuery(){return this.state.query}getRefinements(){return[...this.state.refinements]}getCurrentPage(){return this.state.currentPage}getResults(){return this.state.results}getLoading(){return this.state.loading}getError(){return this.state.error}setQuery(e,t=!0){return this.state.query===e?(c("SearchStateManager: Query unchanged, skipping update",{query:e}),void(t&&this.autoSearch&&(c("SearchStateManager: Query unchanged but triggerSearch=true, triggering search"),this.debouncedSearch()))):""===e&&this.keepResultsOnClear?(c("SearchStateManager: Query cleared, keeping previous results"),this.state.query="",this.state.currentPage=1,void this.notifyListeners()):(this.state.query=e,this.state.currentPage=1,c("SearchStateManager: Query updated",{query:e,triggerSearch:t,autoSearch:this.autoSearch}),this.notifyListeners(),void(this.autoSearch&&t?(c("SearchStateManager: Triggering debounced search"),this.debouncedSearch()):c("SearchStateManager: Search not triggered",{autoSearch:this.autoSearch,triggerSearch:t})))}addRefinement(e,t,n=!0){this.state.refinements.some(n=>n.field===e&&n.value===t)||(this.state.refinements.push({field:e,value:t}),this.state.currentPage=1,c("SearchStateManager: Refinement added",{field:e,value:t}),this.notifyListeners(),this.autoSearch&&n&&this.debouncedSearch())}removeRefinement(e,t,n=!0){const s=this.state.refinements.findIndex(n=>n.field===e&&n.value===t);-1!==s&&(this.state.refinements.splice(s,1),this.state.currentPage=1,c("SearchStateManager: Refinement removed",{field:e,value:t}),this.notifyListeners(),this.autoSearch&&n&&this.debouncedSearch())}clearRefinements(e=!0){0!==this.state.refinements.length&&(this.state.refinements=[],this.state.currentPage=1,c("SearchStateManager: Refinements cleared"),this.notifyListeners(),this.autoSearch&&e&&this.debouncedSearch())}setPage(e,t=!0){this.state.currentPage!==e&&(this.state.currentPage=e,c("SearchStateManager: Page updated",{page:e}),this.notifyListeners(),this.autoSearch&&t&&this.debouncedSearch())}setSortBy(e,t=!0){this.state.sortBy!==e&&(this.state.sortBy=e,this.state.currentPage=1,c("SearchStateManager: Sort updated",{sortBy:e}),this.notifyListeners(),this.autoSearch&&t&&this.debouncedSearch())}setItemsPerPage(e,t=!0){this.state.itemsPerPage!==e&&(this.state.itemsPerPage=e,this.state.currentPage=1,c("SearchStateManager: Items per page updated",{itemsPerPage:e}),this.notifyListeners(),this.autoSearch&&t&&this.debouncedSearch())}async search(e){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.setState({loading:!0,error:null});try{const t=this.buildSearchOptions(e);c("SearchStateManager: Performing search",{query:this.state.query,refinementsCount:this.state.refinements.length,currentPage:this.state.currentPage,sortBy:this.state.sortBy,filter_by:t.filter_by});const n=await this.client.search(this.state.query,t);return this.setState({results:n,loading:!1,error:null}),d("SearchStateManager: Search completed",{query:this.state.query,resultsCount:n?.results?.length||0,totalResults:n?.totalResults||0}),n}catch(e){const t=e instanceof Error?e:new Error(String(e));return this.setState({results:null,loading:!1,error:t}),g("SearchStateManager: Search failed",{query:this.state.query,error:t.message}),null}}buildSearchOptions(e){const t={...this.defaultSearchOptions,page:this.state.currentPage,per_page:this.state.itemsPerPage,...e};if(this.state.sortBy&&"relevance"!==this.state.sortBy&&(t.sort_by=this.state.sortBy),this.state.refinements.length>0){const e={};this.state.refinements.forEach(t=>{e[t.field]||(e[t.field]=[]),e[t.field].push(t.value)});const n=[];Object.entries(e).forEach(([e,t])=>{t.forEach(t=>{n.push(`${e}:${t}`)})}),n.length>0&&(t.filter_by=n.join(" && "))}return t}debouncedSearch(){this.debounceTimer&&clearTimeout(this.debounceTimer),c("SearchStateManager: Scheduling debounced search",{debounceMs:this.debounceMs}),this.debounceTimer=setTimeout(()=>{c("SearchStateManager: Debounce timer fired, calling search()"),this.search()},this.debounceMs)}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){const e=this.getState();this.listeners.forEach(t=>{try{t(e)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("SearchStateManager: Error in listener",{error:t.message})}})}clearResults(){this.setState({results:null,loading:!1,error:null}),c("SearchStateManager: Results explicitly cleared")}getAbTestId(){return this.abTestId}getAbVariant(){return this.abVariant}setAbTest(e,t){this.abTestId=e,this.abVariant=t,c("SearchStateManager: A/B test updated",{abTestId:e,abVariant:t})}buildFilterString(){if(0===this.state.refinements.length)return"";const e={};this.state.refinements.forEach(t=>{e[t.field]||(e[t.field]=[]),e[t.field].push(t.value)});const t=[];return Object.entries(e).forEach(([e,n])=>{n.forEach(n=>{t.push(`${e}:${n}`)})}),t.join(" && ")}async fetchFilters(e){c("SearchStateManager: Fetching filters",{options:e});try{const t=this.buildFilterString(),n=await this.client.getFilters({q:this.state.query||void 0,filter:t||void 0,...e});return d("SearchStateManager: Filters fetched",{filterCount:n?.filters?.length}),n}catch(e){const t=e instanceof Error?e:new Error(String(e));throw g("SearchStateManager: Failed to fetch filters",{error:t.message}),t}}async searchFacetValues(e,t){c("SearchStateManager: Searching facet values",{facetName:e,query:t});try{const n=this.buildFilterString(),s=await this.client.searchFacetValues(e,{q:this.state.query||void 0,filter:n||void 0,facetQuery:t});return d("SearchStateManager: Facet values fetched",{facetName:e,valueCount:s?.values?.length}),s}catch(t){const n=t instanceof Error?t:new Error(String(t));throw g("SearchStateManager: Failed to search facet values",{facetName:e,error:n.message}),n}}async getFiltersSchema(){c("SearchStateManager: Getting filters schema");try{const e=await this.client.getFiltersSchema();return d("SearchStateManager: Filters schema fetched",{fieldCount:e?.fields?.length}),e}catch(e){const t=e instanceof Error?e:new Error(String(e));throw g("SearchStateManager: Failed to get filters schema",{error:t.message}),t}}clear(){this.state={query:"",refinements:[],currentPage:1,itemsPerPage:this.state.itemsPerPage,sortBy:void 0,results:null,loading:!1,error:null},this.notifyListeners()}}const f={colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textSecondary:"#6c757d",border:"#dee2e6",hover:"#f8f9fa",focus:"#007bff",error:"#dc3545",success:"#28a745",warning:"#ffc107"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},borderRadius:{none:"0",small:"0.25rem",medium:"0.375rem",large:"0.5rem",full:"9999px"},shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24)",medium:"0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23)",large:"0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23)"},transitions:{fast:"150ms ease-in-out",normal:"250ms ease-in-out",slow:"350ms ease-in-out"},breakpoints:{sm:"640px",md:"768px",lg:"1024px",xl:"1280px"},zIndex:{dropdown:1e3,modal:2e3,tooltip:3e3}},y=e=>((e,t)=>({colors:{...t.colors,...e.colors},typography:{...t.typography,...e.typography,fontSize:{...t.typography.fontSize,...e.typography?.fontSize}},spacing:{...t.spacing,...e.spacing},borderRadius:e.borderRadius??t.borderRadius,shadows:{...t.shadows,...e.shadows},transitions:{...t.transitions,...e.transitions},breakpoints:{...t.breakpoints,...e.breakpoints},zIndex:{...t.zIndex,...e.zIndex}}))(e,f);class S{constructor(e){c("SearchProvider: Initializing",{hasTheme:!!e.theme,enableAnalytics:!1!==e.enableAnalytics,autoTrackSearch:!1!==e.autoTrackSearch}),this.client=e.client,this.theme=e.theme?y(e.theme):f,this.enableAnalytics=!1!==e.enableAnalytics,this.autoTrackSearch=!1!==e.autoTrackSearch,this.stateManager=new m({client:this.client,autoSearch:!0,debounceMs:300,itemsPerPage:10,defaultSearchOptions:{widget_mode:!0},...e.stateManager}),S.instance=this,d("SearchProvider: Initialized successfully",{hasStateManager:!0,autoSearch:this.stateManager.getState()})}static getInstance(){return S.instance}static setInstance(e){S.instance=e}}S.instance=null;e.ClearRefinements=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("ClearRefinements: container element not found");throw g("ClearRefinements: Initialization failed",{error:e.message}),e}this.container=n,this.options={clearsQuery:t.clearsQuery??!1,resetLabel:t.resetLabel??"Clear all filters",disabledLabel:t.disabledLabel??"No filters applied",includedFields:t.includedFields,excludedFields:t.excludedFields??[],onClear:t.onClear,hideWhenEmpty:t.hideWhenEmpty??!1},this.unsubscribeStateManager=this.provider.stateManager.subscribe(()=>{this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.container.innerHTML=""}getRelevantRefinements(){return this.provider.stateManager.getRefinements().filter(e=>!this.options.excludedFields.includes(e.field)&&!(this.options.includedFields&&!this.options.includedFields.includes(e.field)))}canClear(){const e=this.getRelevantRefinements(),t=this.provider.stateManager.getQuery();return e.length>0||this.options.clearsQuery&&t.length>0}handleClick(){if(!this.canClear())return;const e=this.getRelevantRefinements();if(c("ClearRefinements: Clearing refinements",{count:e.length,clearsQuery:this.options.clearsQuery}),this.options.includedFields||this.options.excludedFields.length>0?e.forEach(e=>{this.provider.stateManager.removeRefinement(e.field,e.value,!1)}):this.provider.stateManager.clearRefinements(!1),this.options.clearsQuery?this.provider.stateManager.setQuery("",!0):e.length>0&&this.provider.stateManager.search(),this.options.onClear)try{this.options.onClear()}catch(e){const t=e instanceof Error?e:new Error(String(e));g("ClearRefinements: Error in onClear callback",{error:t.message})}}render(){this.container.innerHTML="";const e=this.canClear();if(this.options.hideWhenEmpty&&!e)return;const t=document.createElement("button");t.type="button",t.textContent=e?this.options.resetLabel:this.options.disabledLabel,t.disabled=!e,t.style.cssText=this.getButtonStyle(e),t.setAttribute("aria-label",e?this.options.resetLabel:this.options.disabledLabel),t.addEventListener("click",()=>this.handleClick()),this.container.appendChild(t)}get theme(){return this.provider.theme}getButtonStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n background-color: ${e?this.theme.colors.primary:this.theme.colors.hover};\n color: ${e?"#ffffff":this.theme.colors.textSecondary};\n border: none;\n border-radius: ${t};\n cursor: ${e?"pointer":"not-allowed"};\n opacity: ${e?"1":"0.6"};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.CurrentRefinements=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("CurrentRefinements: container element not found");throw g("CurrentRefinements: Initialization failed",{error:e.message}),e}this.container=n,this.options={showClearAll:!1!==t.showClearAll,refinements:t.refinements||[],onRefinementClear:t.onRefinementClear,onClearAll:t.onClearAll},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{this.options.refinements=e.refinements.map(e=>({field:e.field,value:e.value,label:e.field})),this.render()}),this.render()}update(e){void 0!==e.refinements&&(this.options.refinements=e.refinements,this.render())}render(){if(this.container.innerHTML="",!this.options.refinements||0===this.options.refinements.length)return;const e=document.createElement("div");if(e.style.cssText=this.getContainerStyle(),this.options.refinements.forEach((t,n)=>{const s=document.createElement("div");s.style.cssText=this.getItemStyle();const i=document.createElement("span");i.textContent=`${t.label||t.field}: `,i.style.cssText=this.getLabelStyle(),s.appendChild(i);const r=document.createElement("span");r.textContent=t.displayValue||t.value,r.style.cssText=this.getValueStyle(),s.appendChild(r);const o=document.createElement("button");o.innerHTML="×",o.type="button",o.style.cssText=this.getClearButtonStyle(),o.setAttribute("aria-label",`Clear ${t.field} filter`);o.addEventListener("click",e=>{if(e.preventDefault(),e.stopPropagation(),this.provider.stateManager.removeRefinement(t.field,t.value),this.options.onRefinementClear){c("CurrentRefinements: Refinement cleared",{field:t.field,value:t.value});try{this.options.onRefinementClear(t.field,t.value)}catch(e){const n=e instanceof Error?e:new Error(String(e));g("CurrentRefinements: Error in onRefinementClear callback",{field:t.field,value:t.value,error:n.message})}}},{passive:!1}),s.appendChild(o),e.appendChild(s)}),this.options.showClearAll&&this.options.refinements.length>1){const t=document.createElement("button");t.textContent="Clear all",t.style.cssText=this.getClearAllButtonStyle();const n=e=>{e.preventDefault(),e.stopPropagation(),this.provider.stateManager.clearRefinements(),this.options.onClearAll&&this.options.onClearAll()};t.addEventListener("click",n,{passive:!1}),e.appendChild(t)}this.container.appendChild(e)}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: ${this.theme.spacing.small};\n `}getItemStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n display: inline-flex;\n align-items: center;\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n background-color: ${this.theme.colors.hover};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n font-size: ${this.theme.typography.fontSize.small};\n `}getLabelStyle(){return`\n margin-right: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n `}getValueStyle(){return`\n margin-right: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getClearButtonStyle(){return`\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.full||"50%"};\n background-color: transparent;\n border: none;\n color: ${this.theme.colors.text};\n cursor: pointer;\n font-size: ${this.theme.typography.fontSize.medium};\n line-height: 1;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getClearAllButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.primary};\n background: transparent;\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n cursor: pointer;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.Facets=class{constructor(e,t){this.expandedFacets={},this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("Facets: container element not found");this.container=n,this.options={maxItems:t.maxItems||10,showMore:!1!==t.showMore,results:t.results,facets:t.facets,onFacetChange:t.onFacetChange},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.results&&(this.options.results=e.results),this.render()}),this.render()}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.facets&&(this.options.facets=e.facets),this.render()}render(){this.container.innerHTML="";const e=this.getFacets();0!==e.length?(c("Facets: Rendering",e.length,"facets",e),e.forEach((e,t)=>{const n=document.createElement("div");n.style.cssText=this.getFacetStyle();const s=document.createElement("div");s.style.cssText=this.getFacetHeaderStyle(),s.textContent=e.label||e.field,n.appendChild(s);const i=document.createElement("div");i.style.cssText=this.getFacetListStyle();const r=this.expandedFacets[e.field]||!1;if((r?e.items:e.items.slice(0,this.options.maxItems)).forEach((t,n)=>{const s=document.createElement("div");s.style.cssText=this.getFacetItemStyle(t.selected||!1);const r=this.provider.stateManager.getRefinements().some(n=>n.field===e.field&&n.value===t.value)||t.selected||!1,o=document.createElement("input");o.type="checkbox",o.checked=r,o.addEventListener("change",()=>{const n=o.checked;n?this.provider.stateManager.addRefinement(e.field,t.value):this.provider.stateManager.removeRefinement(e.field,t.value),this.options.onFacetChange&&this.options.onFacetChange(e.field,t.value,n)}),s.appendChild(o);const a=document.createElement("label");a.textContent=t.value,a.style.cssText=this.getFacetItemLabelStyle(),a.setAttribute("for",`facet-${e.field}-${n}`),o.id=`facet-${e.field}-${n}`;a.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o.checked=!o.checked,o.dispatchEvent(new Event("change",{bubbles:!0}))},{passive:!1}),s.appendChild(a);const l=document.createElement("span");l.textContent=`(${t.count})`,l.style.cssText=this.getFacetItemCountStyle(),s.appendChild(l),i.appendChild(s)}),this.options.showMore&&e.items.length>this.options.maxItems){const t=document.createElement("button");t.textContent=r?"Show less":`Show more (${e.items.length-this.options.maxItems})`,t.style.cssText=this.getShowMoreStyle();const n=t=>{t.preventDefault(),t.stopPropagation(),this.expandedFacets[e.field]=!r,this.render()};t.addEventListener("click",n,{passive:!1}),i.appendChild(t)}n.appendChild(i),this.container.appendChild(n)})):c("Facets: No facets found in results",{hasResults:!!this.options.results,hasFacetsOption:!!this.options.facets,resultsKeys:this.options.results?Object.keys(this.options.results):[]})}getFacets(){if(this.options.facets&&Array.isArray(this.options.facets))return this.options.facets;const e=this.options.results;if(!e)return[];let t=null;if(e&&"object"==typeof e&&("data"in e&&e.data&&"object"==typeof e.data&&"facets"in e.data&&Array.isArray(e.data.facets)&&(t=e.data.facets),!t&&"facets"in e&&Array.isArray(e.facets)&&(t=e.facets)),!t||!Array.isArray(t))return[];const n=[];for(const e of t){const t=e.field_name||e.field||e.name;if(!t)continue;const s=e.label||t,i=[];if(Array.isArray(e.counts))for(const t of e.counts){const e=t.value,n=t.count;null!=e&&null!=n&&i.push({value:String(e),count:Number(n),selected:Boolean(t.selected)})}i.length>0&&n.push({field:t,label:s,items:i})}return n}get theme(){return this.provider.theme}getFacetStyle(){return`\n margin-bottom: ${this.theme.spacing.medium};\n `}getFacetHeaderStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.bold||700};\n margin-bottom: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getFacetListStyle(){return`\n display: flex;\n flex-direction: column;\n gap: ${this.theme.spacing.small};\n `}getFacetItemStyle(e){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n padding: ${this.theme.spacing.small};\n cursor: pointer;\n background-color: ${e?this.theme.colors.hover:"transparent"};\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getFacetItemLabelStyle(){return`\n flex: 1;\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n cursor: pointer;\n `}getFacetItemCountStyle(){return`\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n opacity: 0.7;\n `}getShowMoreStyle(){return"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small,`\n padding: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.primary};\n background: none;\n border: none;\n cursor: pointer;\n text-align: left;\n margin-top: ${this.theme.spacing.small};\n `}},e.HitsPerPage=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("HitsPerPage: container element not found");throw g("HitsPerPage: Initialization failed",{error:e.message}),e}this.container=n;const s=t.items.find(e=>e.default)||t.items[0];this.currentValue=s?.value||10,this.options={items:t.items,label:t.label??"Show",onHitsPerPageChange:t.onHitsPerPageChange},this.provider.stateManager.setItemsPerPage(this.currentValue,!1),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.itemsPerPage!==this.currentValue&&(this.currentValue=e.itemsPerPage,this.render())}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.container.innerHTML=""}update(e){e.items&&(this.options.items=e.items,this.render())}render(){this.container.innerHTML="";const e=document.createElement("div");if(e.style.cssText=this.getContainerStyle(),this.options.label){const t=document.createElement("label");t.textContent=this.options.label,t.style.cssText=this.getLabelStyle(),e.appendChild(t)}const t=document.createElement("select");t.value=this.currentValue.toString(),t.style.cssText=this.getSelectStyle(),t.setAttribute("aria-label","Results per page"),t.addEventListener("change",e=>{const t=e.target,n=parseInt(t.value,10);if(this.currentValue=n,c("HitsPerPage: Value changed",{value:n}),this.provider.stateManager.setItemsPerPage(n,!1),this.provider.stateManager.setPage(1,!0),this.options.onHitsPerPageChange)try{this.options.onHitsPerPageChange(n)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("HitsPerPage: Error in onHitsPerPageChange callback",{value:n,error:t.message})}}),this.options.items.forEach(e=>{const n=document.createElement("option");n.value=e.value.toString(),n.textContent=e.label,e.value===this.currentValue&&(n.selected=!0),t.appendChild(n)}),e.appendChild(t),this.container.appendChild(e)}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n `}getLabelStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n `}getSelectStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n cursor: pointer;\n outline: none;\n `}},e.InfiniteHits=class{constructor(e,t){this.accumulatedHits=[],this.isLoadingMore=!1,this.currentPage=1,this.observer=null,this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("InfiniteHits: container element not found");throw g("InfiniteHits: Initialization failed",{error:e.message}),e}this.container=n,this.options={renderHit:t.renderHit,renderEmpty:t.renderEmpty,showMoreButton:!1!==t.showMoreButton,useInfiniteScroll:t.useInfiniteScroll??!1,scrollThreshold:t.scrollThreshold??.1,fieldMapping:t.fieldMapping,showMoreLabel:t.showMoreLabel??"Show more",onHitClick:t.onHitClick},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{const t=e.currentPage,n=this.extractHits(e.results);1===t?(this.accumulatedHits=n,this.currentPage=1):t>this.currentPage&&(this.accumulatedHits=[...this.accumulatedHits,...n],this.currentPage=t),this.isLoadingMore=!1,this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.observer&&(this.observer.disconnect(),this.observer=null),this.container.innerHTML=""}extractHits(e){return e?e.results?e.results:e.hits?e.hits:Array.isArray(e)?e:[]:[]}get isLastPage(){const e=this.provider.stateManager.getState(),t=e.results?.totalResults||e.results?.found||0,n=e.itemsPerPage||10,s=Math.ceil(t/n);return e.currentPage>=s}handleShowMore(){if(this.isLastPage||this.isLoadingMore)return;this.isLoadingMore=!0;const e=this.provider.stateManager.getCurrentPage()+1;c("InfiniteHits: Loading more",{nextPage:e}),this.provider.stateManager.setPage(e),this.render()}render(){this.container.innerHTML="";const e=this.provider.stateManager.getState();if(e.loading&&0===this.accumulatedHits.length)return;if(!e.loading&&0===this.accumulatedHits.length){const e=this.options.renderEmpty?this.options.renderEmpty():this.createDefaultEmpty();return void this.container.appendChild(e)}const t=document.createElement("div");if(this.accumulatedHits.forEach((e,n)=>{const s=this.options.renderHit?this.options.renderHit(e,n):this.createDefaultHit(e,n);t.appendChild(s)}),this.container.appendChild(t),this.options.showMoreButton&&!this.options.useInfiniteScroll&&!this.isLastPage){const e=this.createShowMoreButton();this.container.appendChild(e)}if(this.options.useInfiniteScroll&&!this.isLastPage){const e=document.createElement("div");e.style.cssText="height: 1px; visibility: hidden;",this.container.appendChild(e),this.setupIntersectionObserver(e)}}setupIntersectionObserver(e){this.observer&&this.observer.disconnect(),this.observer=new IntersectionObserver(e=>{!e[0].isIntersecting||this.isLastPage||this.isLoadingMore||this.handleShowMore()},{threshold:this.options.scrollThreshold}),this.observer.observe(e)}createDefaultHit(e,t){const n=document.createElement("div");n.style.cssText=this.getHitStyle();if(this.options.fieldMapping){const t=this.extractField(e,"image");if(t){const s=document.createElement("img");s.src=t,s.alt=this.extractField(e,"title")||"",s.style.cssText=this.getImageStyle(),n.appendChild(s)}const s=document.createElement("div");s.style.cssText="flex: 1;";const i=this.extractField(e,"title");if(i){const e=document.createElement("h3");e.textContent=i,e.style.cssText=this.getTitleStyle(),s.appendChild(e)}const r=this.extractField(e,"description");if(r){const e=document.createElement("p");e.textContent=r,e.style.cssText=this.getDescriptionStyle(),s.appendChild(e)}const o=this.extractFieldValue(e,"price");if(null!=o&&""!==o){const e=document.createElement("span"),t="number"==typeof o?o.toFixed(2):String(o);e.textContent=`$${t}`,e.style.cssText=this.getPriceStyle(),s.appendChild(e)}n.appendChild(s)}else{const t=document.createElement("div");t.style.cssText="flex: 1;";Object.keys(e).slice(0,5).forEach(n=>{const s=e[n];if(null!=s&&"object"!=typeof s){const e=document.createElement("div");e.innerHTML=`<strong>${n}:</strong> ${String(s)}`,e.style.cssText=`margin-bottom: ${this.theme.spacing.small}; font-size: ${this.theme.typography.fontSize.small};`,t.appendChild(e)}}),n.appendChild(t)}return this.options.onHitClick&&(n.style.cursor="pointer",n.addEventListener("click",()=>this.options.onHitClick(e,t))),n}createDefaultEmpty(){const e=document.createElement("div");return e.textContent="No results found",e.style.cssText=`\n padding: ${this.theme.spacing.large};\n text-align: center;\n color: ${this.theme.colors.textSecondary};\n `,e}createShowMoreButton(){const e=document.createElement("button");return e.type="button",e.textContent=this.options.showMoreLabel,e.disabled=this.isLoadingMore,e.style.cssText=this.getShowMoreButtonStyle(),e.addEventListener("click",()=>this.handleShowMore()),e}extractField(e,t){if(!this.options.fieldMapping||!this.options.fieldMapping[t]){const n=e[t];return null!=n?String(n):""}const n=this.options.fieldMapping[t];if("string"!=typeof n){const n=e[t];return null!=n?String(n):""}const s=e[n];return null!=s?String(s):""}extractFieldValue(e,t){if(!this.options.fieldMapping||!this.options.fieldMapping[t]){const n=e[t];return null!=n?n:void 0}const n=this.options.fieldMapping[t];if("string"!=typeof n){const n=e[t];return null!=n?n:void 0}const s=e[n];return null!=s?s:void 0}get theme(){return this.provider.theme}getHitStyle(){return"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small,`\n display: flex;\n gap: ${this.theme.spacing.medium};\n padding: ${this.theme.spacing.medium};\n border-bottom: 1px solid ${this.theme.colors.border};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getImageStyle(){return`\n width: 80px;\n height: 80px;\n object-fit: cover;\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small};\n `}getTitleStyle(){return`\n margin: 0;\n margin-bottom: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.semibold||600};\n color: ${this.theme.colors.text};\n `}getDescriptionStyle(){return`\n margin: 0;\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.textSecondary};\n line-height: ${this.theme.typography.lineHeight?.normal||1.5};\n `}getPriceStyle(){return`\n display: inline-block;\n margin-top: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.bold||700};\n color: ${this.theme.colors.primary};\n `}getShowMoreButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n display: block;\n width: 100%;\n padding: ${this.theme.spacing.medium};\n margin-top: ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n background-color: ${this.isLoadingMore?this.theme.colors.hover:this.theme.colors.primary};\n color: ${this.isLoadingMore?this.theme.colors.textSecondary:"#ffffff"};\n border: none;\n border-radius: ${e};\n cursor: ${this.isLoadingMore?"not-allowed":"pointer"};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.Pagination=class{constructor(e,t){this.unsubscribeStateManager=null,console.log("Pagination: Constructor called",{options:t}),this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("Pagination: container element not found");throw g("Pagination: Initialization failed",{error:e.message}),e}console.log("Pagination: Container found",{container:n,containerId:n.id,containerTag:n.tagName}),this.container=n,this.currentPage=t.currentPage||1,this.options={itemsPerPage:t.itemsPerPage||10,showFirstLast:!1!==t.showFirstLast,showPrevNext:!1!==t.showPrevNext,results:t.results,currentPage:t.currentPage||1,onPageChange:t.onPageChange};this.container.addEventListener("click",e=>{const t=e.target;if(console.log("Pagination: Container clicked",{target:t.tagName,targetClass:t.className,hasDataPage:t.hasAttribute("data-page"),closestButton:t.closest("button[data-page]")}),"SPAN"===t.tagName||"DIV"===t.tagName){if(!t.closest("button[data-page]"))return}const n="BUTTON"===t.tagName&&t.hasAttribute("data-page")?t:t.closest("button[data-page]");if(n){e.preventDefault(),e.stopPropagation();const t=n.getAttribute("data-page"),s=t?parseInt(t,10):0;if(console.log("Pagination: Button found",{page:s,currentPage:this.currentPage,pageStr:t,button:n,isValid:s>0&&s!==this.currentPage}),s>0)if(console.log("Pagination: Processing page change",{page:s,currentPage:this.currentPage,willUpdate:s!==this.currentPage}),s!==this.currentPage){if(this.provider.stateManager.setPage(s),this.options.onPageChange)try{this.options.onPageChange(s)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("Pagination: Error in onPageChange callback",{page:s,error:t.message})}}else console.log("Pagination: Page is already current, skipping update",{page:s});else console.warn("Pagination: Invalid page number",{page:s,pageStr:t,button:n})}else console.log("Pagination: Click not on a button",{target:t.tagName})},{passive:!1}),console.log("Pagination: Event delegation listener attached to container",{container:this.container}),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.results&&(this.options.results=e.results),e.currentPage!==this.currentPage&&(this.currentPage=e.currentPage),this.render()}),this.render()}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.currentPage&&(this.currentPage=e.currentPage),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}render(){console.log("🔵 Pagination.render() START",{container:this.container,containerId:this.container.id,currentPage:this.currentPage,hasResults:!!this.options.results}),this.container.innerHTML="";const e=this.getTotalPages();if(console.log("🔵 Pagination: Total pages calculated",{totalPages:e}),e<=1)return console.log("🔵 Pagination: NOT RENDERING - totalPages <= 1",{totalPages:e}),void c("Pagination: Not rendering, totalPages <= 1",{totalPages:e});console.log("🔵 Pagination: WILL RENDER",{currentPage:this.currentPage,totalPages:e,hasResults:!!this.options.results}),c("Pagination: Rendering",{currentPage:this.currentPage,totalPages:e,hasResults:!!this.options.results});const t=document.createElement("div");if(t.style.cssText=this.getContainerStyle(),t.setAttribute("data-pagination-wrapper","true"),console.log("Pagination: Created paginationDiv",{paginationDiv:t,style:t.style.cssText,container:this.container}),this.options.showFirstLast&&this.currentPage>1){const e=this.createButton("First",1);t.appendChild(e)}if(this.options.showPrevNext&&this.currentPage>1){const e=this.createButton("Previous",this.currentPage-1);t.appendChild(e)}let n,s;if(e<=5)n=1,s=e;else{const t=Math.floor(2.5);this.currentPage<=t+1?(n=1,s=5):this.currentPage>=e-t?(n=e-5+1,s=e):(n=this.currentPage-t,s=this.currentPage+t)}if(n>1){const e=document.createElement("span");e.textContent="...",e.style.cssText=`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n `,t.appendChild(e)}console.log("🔵 Pagination: Rendering page buttons",{startPage:n,endPage:s,currentPage:this.currentPage});for(let e=n;e<=s;e++){console.log("🔵 Pagination: Creating page button",{i:e,isActive:e===this.currentPage});const n=this.createButton(String(e),e,e===this.currentPage);t.appendChild(n),console.log("🔵 Pagination: Page button appended",{page:e,button:n})}if(s<e){const e=document.createElement("span");e.textContent="...",e.style.cssText=`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n `,t.appendChild(e)}if(this.options.showPrevNext&&this.currentPage<e){const e=this.createButton("Next",this.currentPage+1);t.appendChild(e)}if(this.options.showFirstLast&&this.currentPage<e){const n=this.createButton("Last",e);t.appendChild(n)}console.log("🔵 Pagination: About to append paginationDiv to container",{paginationDiv:t,container:this.container,containerChildrenBefore:this.container.children.length,paginationDivChildren:t.children.length}),this.container.appendChild(t),console.log("🔵 Pagination: paginationDiv appended to container",{containerChildrenAfter:this.container.children.length,containerHTML:this.container.innerHTML.substring(0,300)});const i=this.container.querySelectorAll("button[data-page]");console.log("🔵 Pagination: Render complete - buttons in DOM",{buttonCount:i.length,buttons:Array.from(i).map(e=>{const t=e;return{text:t.textContent,page:t.getAttribute("data-page"),element:t,parent:t.parentElement?.tagName}})}),console.log("🔵 Pagination: Testing direct click handler");const r=this.container.querySelector("button[data-page]");r?(console.log("🔵 Pagination: Found test button, adding DIRECT listener",{testButton:r,page:r.getAttribute("data-page"),text:r.textContent}),r.addEventListener("click",e=>{console.log("🟢🟢🟢 DIRECT BUTTON CLICK HANDLER FIRED! 🟢🟢🟢",{e:e,button:r,page:r.getAttribute("data-page"),target:e.target}),e.preventDefault(),e.stopPropagation()},{passive:!1,capture:!0}),console.log("🔵 Pagination: Direct listener attached to test button")):console.warn("🔴 Pagination: NO TEST BUTTON FOUND for direct listener!"),console.log("🔵 Pagination.render() END")}getTotalPages(){if(!this.options.results)return 0;let e;if("number"==typeof this.options.results.totalResults)e=this.options.results.totalResults;else if("number"==typeof this.options.results.total)e=this.options.results.total;else{const t=this.options.results.results?.length||0;u("Pagination: Using results array length as total (totalResults not found)",{resultsLength:t,responseKeys:Object.keys(this.options.results)}),e=t}const t=Math.ceil(e/this.options.itemsPerPage);return c("Pagination: Calculating total pages",{total:e,itemsPerPage:this.options.itemsPerPage,totalPages:t,currentPage:this.currentPage}),t}createButton(e,t,n=!1){const s=document.createElement("button");return s.textContent=e,s.style.cssText=this.getButtonStyle(n),s.type="button",s.setAttribute("data-page",String(t)),s}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n flex-wrap: wrap;\n `}getButtonStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium,n=this.theme.transitions?.fast||"150ms ease-in-out";return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${t};\n background-color: ${e?this.theme.colors.primary:this.theme.colors.background};\n color: ${e?"#ffffff":this.theme.colors.text};\n cursor: pointer;\n transition: ${n};\n `}},e.QuerySuggestions=class{constructor(e,t){this.suggestions=[],this.loading=!1,this.error=null,this.selectedIndex=-1,this.debounceTimer=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("QuerySuggestions: container element not found");this.container=n,this.options={query:t.query||"",maxSuggestions:t.maxSuggestions||10,debounceMs:t.debounceMs||300,minQueryLength:t.minQueryLength||2,showTitle:t.showTitle||!1,title:t.title||"Suggestions",onSuggestionClick:t.onSuggestionClick};const s=this.options.query??"";s.length>=this.options.minQueryLength&&this.loadSuggestions(s)}update(e){void 0!==e.query&&(this.options.query=e.query,this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.options.query&&this.options.query.length>=this.options.minQueryLength?this.loadSuggestions(this.options.query):(this.suggestions=[],this.render())},this.options.debounceMs))}async loadSuggestions(e){this.loading=!0,this.error=null;try{const t=await this.provider.client.getSuggestions(e,this.options.maxSuggestions),n=Array.isArray(t)?t:[];this.suggestions=n.map(e=>{const t=e.query??e.text??e,n=void 0!==e.popularity?e.popularity:void 0!==e.count?e.count:void 0;return{query:"string"==typeof t?t:String(t),count:"number"==typeof n?n:void 0,metadata:e}}).slice(0,this.options.maxSuggestions),this.loading=!1,this.render(),c("QuerySuggestions: Suggestions loaded",{query:this.options.query,count:this.suggestions.length})}catch(e){const t=e instanceof Error?e:new Error(String(e));g("QuerySuggestions: Failed to load suggestions",{query:this.options.query,error:t.message,stack:t.stack}),this.error=t,this.loading=!1,this.render()}}render(){if(this.container.innerHTML="",!this.options.query||this.options.query.length<this.options.minQueryLength)return;if(this.error||0===this.suggestions.length){const e=document.createElement("div");return e.style.cssText=this.getEmptyStyle(),e.textContent="No suggestions available",void this.container.appendChild(e)}if(this.options.showTitle){const e=document.createElement("div");e.style.cssText=this.getTitleStyle(),e.textContent=this.options.title,this.container.appendChild(e)}const e=document.createElement("div");e.style.cssText=this.getListStyle(),this.suggestions.forEach((t,n)=>{const s=document.createElement("div");s.style.cssText=this.getSuggestionStyle(n===this.selectedIndex);s.addEventListener("click",e=>{if(e.preventDefault(),e.stopPropagation(),this.options.onSuggestionClick){c("QuerySuggestions: Suggestion clicked",{suggestion:t.query});try{this.options.onSuggestionClick(t.query)}catch(e){const n=e instanceof Error?e:new Error(String(e));g("QuerySuggestions: Error in onSuggestionClick callback",{suggestion:t.query,error:n.message})}}},{passive:!1}),s.addEventListener("mouseenter",()=>{this.selectedIndex=n,this.render()}),s.addEventListener("mouseleave",()=>{this.selectedIndex=-1,this.render()});const i=document.createElement("span");if(i.textContent=t.query,s.appendChild(i),void 0!==t.count){const e=document.createElement("span");e.textContent=` (${t.count})`,e.style.cssText=this.getCountStyle(),s.appendChild(e)}e.appendChild(s)}),this.container.appendChild(e)}get theme(){return this.provider.theme}getTitleStyle(){return`\n font-size: ${this.theme.typography.fontSize.large};\n font-weight: bold;\n margin-bottom: ${this.theme.spacing.medium};\n color: ${this.theme.colors.text};\n `}getEmptyStyle(){return`\n padding: ${this.theme.spacing.medium};\n text-align: center;\n color: ${this.theme.colors.text};\n opacity: 0.6;\n `}getListStyle(){return"\n display: flex;\n flex-direction: column;\n "}getSuggestionStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.medium};\n cursor: pointer;\n border-radius: ${t};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n background-color: ${e?this.theme.colors.hover:"transparent"};\n margin-bottom: ${this.theme.spacing.small};\n `}getCountStyle(){return`\n opacity: 0.6;\n margin-left: ${this.theme.spacing.small};\n `}destroy(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.container.innerHTML=""}},e.RangeInput=class{constructor(e,t){this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("RangeInput: container element not found");throw g("RangeInput: Initialization failed",{error:e.message}),e}this.container=n,this.internalMin=t.currentMin,this.internalMax=t.currentMax,this.options={field:t.field,label:t.label??"",min:t.min??0,max:t.max??100,step:t.step??1,showApplyButton:!1!==t.showApplyButton,placeholder:t.placeholder??{min:"Min",max:"Max"},currentMin:t.currentMin,currentMax:t.currentMax,onRangeChange:t.onRangeChange},this.render()}update(e){void 0!==e.currentMin&&(this.internalMin=e.currentMin,this.options.currentMin=e.currentMin),void 0!==e.currentMax&&(this.internalMax=e.currentMax,this.options.currentMax=e.currentMax),this.render()}render(){if(this.container.innerHTML="",this.options.label){const e=document.createElement("label");e.textContent=this.options.label,e.style.cssText=this.getLabelStyle(),this.container.appendChild(e)}const e=document.createElement("div");e.style.cssText=this.getInputGroupStyle();const t=document.createElement("input");t.type="number",t.min=this.options.min?.toString()||"",t.max=this.options.max?.toString()||"",t.step=this.options.step.toString(),t.value=void 0!==this.internalMin?this.internalMin.toString():"",t.placeholder=this.options.placeholder?.min??"Min",t.style.cssText=this.getInputStyle(),t.addEventListener("input",e=>{const t=e.target,n=""===t.value?void 0:parseFloat(t.value);if(this.internalMin=n,!this.options.showApplyButton&&(this.updateStateManager(n,this.internalMax),this.options.onRangeChange)){c("RangeInput: Min value changed",{field:this.options.field,min:n,max:this.internalMax});try{this.options.onRangeChange(n,this.internalMax)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("RangeInput: Error in onRangeChange callback",{field:this.options.field,error:t.message})}}}),e.appendChild(t);const n=document.createElement("span");n.textContent="to",n.style.cssText=this.getSeparatorStyle(),e.appendChild(n);const s=document.createElement("input");if(s.type="number",s.min=this.options.min?.toString()||"",s.max=this.options.max?.toString()||"",s.step=this.options.step.toString(),s.value=void 0!==this.internalMax?this.internalMax.toString():"",s.placeholder=this.options.placeholder?.max??"Max",s.style.cssText=this.getInputStyle(),s.addEventListener("input",e=>{const t=e.target,n=""===t.value?void 0:parseFloat(t.value);if(this.internalMax=n,!this.options.showApplyButton&&(this.updateStateManager(this.internalMin,n),this.options.onRangeChange)){c("RangeInput: Max value changed",{field:this.options.field,min:this.internalMin,max:n});try{this.options.onRangeChange(this.internalMin,n)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("RangeInput: Error in onRangeChange callback",{field:this.options.field,error:t.message})}}}),e.appendChild(s),this.options.showApplyButton){const t=document.createElement("button");t.textContent="Apply",t.style.cssText=this.getApplyButtonStyle();const n=e=>{if(e.preventDefault(),e.stopPropagation(),this.updateStateManager(this.internalMin,this.internalMax),this.options.onRangeChange){c("RangeInput: Apply button clicked",{field:this.options.field,min:this.internalMin,max:this.internalMax});try{this.options.onRangeChange(this.internalMin,this.internalMax)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("RangeInput: Error in onRangeChange callback",{field:this.options.field,error:t.message})}}};t.addEventListener("click",n,{passive:!1}),e.appendChild(t)}if(this.hasValue()){const t=document.createElement("button");t.textContent="Reset",t.style.cssText=this.getResetButtonStyle();const n=e=>{e.preventDefault(),e.stopPropagation(),this.internalMin=void 0,this.internalMax=void 0;this.provider.stateManager.getRefinements().forEach(e=>{e.field===this.options.field&&this.provider.stateManager.removeRefinement(e.field,e.value)}),this.render(),this.options.onRangeChange&&this.options.onRangeChange(void 0,void 0)};t.addEventListener("click",n,{passive:!1}),e.appendChild(t)}this.container.appendChild(e)}hasValue(){return void 0!==this.internalMin||void 0!==this.internalMax}updateStateManager(e,t){this.provider.stateManager.getRefinements().forEach(e=>{e.field===this.options.field&&this.provider.stateManager.removeRefinement(e.field,e.value,!1)}),void 0!==e&&this.provider.stateManager.addRefinement(this.options.field,`>=${e}`,!1),void 0!==t&&this.provider.stateManager.addRefinement(this.options.field,`<=${t}`,!1),void 0===e&&void 0===t||this.provider.stateManager.search()}get theme(){return this.provider.theme}getLabelStyle(){return`\n display: block;\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n margin-bottom: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getInputGroupStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n flex-wrap: wrap;\n `}getInputStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n flex: 1;\n min-width: 80px;\n padding: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n outline: none;\n `}getSeparatorStyle(){return`\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n font-size: ${this.theme.typography.fontSize.medium};\n `}getApplyButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n background-color: ${this.theme.colors.primary};\n color: #ffffff;\n border: none;\n border-radius: ${e};\n cursor: pointer;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getResetButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n background-color: transparent;\n color: ${this.theme.colors.text};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n cursor: pointer;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.RatingDisplay=s,e.SearchBar=class{constructor(e,t){this.suggestions=[],this.richSuggestionsData=null,this.selectedIndex=-1,this.debounceTimer=null,this.isFocused=!1,this.unsubscribeStateManager=null,e instanceof S?(this.provider=e,this.client=this.provider.client):(this.provider=new S({client:e}),this.client=e);const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("SearchBar: container element not found");this.container=n,this.options={placeholder:t.placeholder||"Powered by Seekora",showSuggestions:!1!==t.showSuggestions,minQueryLength:t.minQueryLength||1,maxSuggestions:t.maxSuggestions||10,debounceMs:t.debounceMs||300,enableRichSuggestions:!1!==t.enableRichSuggestions,onSearch:t.onSearch,onSuggestionSelect:t.onSuggestionSelect,onProductClick:t.onProductClick,onBrandClick:t.onBrandClick,searchOptions:t.searchOptions},this.render(),this.attachEventListeners(),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{if(this.input.value!==e.query&&(this.input.value=e.query),e.results){const t=e.results,n=t.processingTimeMS||t.data?.processingTimeMS||t.data?.data?.processingTimeMS;void 0!==n?(this.responseTimeElement.textContent=`${n}ms`,this.responseTimeElement.style.display="inline"):this.responseTimeElement.style.display="none"}else this.responseTimeElement.style.display="none";e.results&&this.options.onSearch&&this.options.onSearch(e.query,e.results)})}render(){this.container.style.position="relative",this.container.style.display="flex",this.container.style.alignItems="center",this.inputWrapper=document.createElement("div"),this.inputWrapper.style.cssText="position: relative; flex: 1; display: flex; align-items: center;",this.input=document.createElement("input"),this.input.type="text",this.input.placeholder=this.options.placeholder,this.input.style.cssText=this.getInputStyle(),this.injectPlaceholderStyles(),this.inputWrapper.appendChild(this.input),this.responseTimeElement=document.createElement("span"),this.responseTimeElement.style.cssText=this.getResponseTimeStyle(),this.responseTimeElement.style.display="none",this.inputWrapper.appendChild(this.responseTimeElement),this.container.appendChild(this.inputWrapper),this.suggestionsContainer=document.createElement("div"),this.suggestionsContainer.style.cssText=this.getSuggestionsContainerStyle(),this.suggestionsContainer.style.display="none",this.container.appendChild(this.suggestionsContainer)}injectPlaceholderStyles(){const e=this.provider.theme;this.input.id||(this.input.id="seekora-search-input-"+Math.random().toString(36).substr(2,9));const t=`seekora-searchbar-placeholder-${this.input.id}`,n=document.getElementById(t);n&&n.remove();const s=document.createElement("style");s.id=t;const i=e.colors.textSecondary||e.colors.text;s.textContent=`\n #${this.input.id}::placeholder {\n color: ${i};\n opacity: 0.6;\n }\n `,document.head.appendChild(s)}attachEventListeners(){this.input.addEventListener("input",e=>{const t=e.target.value;this.handleInputChange(t)}),this.input.addEventListener("focus",()=>{this.isFocused=!0,this.options.showSuggestions&&this.options.enableRichSuggestions?(console.log("🔍 SearchBar: Input focused, fetching empty query suggestions"),this.handleInputChange("")):this.updateSuggestionsVisibility()}),this.input.addEventListener("blur",e=>{const t=e.relatedTarget;t&&this.suggestionsContainer.contains(t)||setTimeout(()=>{this.suggestionsContainer.contains(document.activeElement)||(this.isFocused=!1,this.updateSuggestionsVisibility(),this.selectedIndex=-1)},100)}),this.input.addEventListener("keydown",e=>{this.handleKeyDown(e)})}handleInputChange(e){this.selectedIndex=-1,this.debounceTimer&&clearTimeout(this.debounceTimer);const t=this.options.enableRichSuggestions;e.trim().length;const n=e.length>=this.options.minQueryLength;return this.options.showSuggestions&&(t||n)?void(this.debounceTimer=setTimeout(async()=>{try{if(this.options.enableRichSuggestions)console.log("🚀 SearchBar: enableRichSuggestions is TRUE, calling fetchRichSuggestions for query:",e||"(empty)"),await this.fetchRichSuggestions(e);else{console.log("⚠️ SearchBar: enableRichSuggestions is FALSE, using basic suggestions");const t=await this.client.getSuggestions(e,this.options.maxSuggestions),n=Array.isArray(t)?t:[];this.suggestions=n.map(e=>{const t=e.query??e.text??e,n=void 0!==e.popularity?e.popularity:void 0!==e.count?e.count:void 0;return{query:"string"==typeof t?t:String(t),count:"number"==typeof n?n:void 0,metadata:e}}),this.richSuggestionsData=null}this.renderSuggestions()}catch(e){g("Error fetching suggestions:",e),this.suggestions=[],this.richSuggestionsData=null,this.renderSuggestions()}},this.options.debounceMs)):(this.suggestions=[],void this.renderSuggestions())}handleKeyDown(e){switch(e.key){case"ArrowDown":e.preventDefault(),this.suggestions.length>0&&(this.selectedIndex=this.selectedIndex<this.suggestions.length-1?this.selectedIndex+1:this.selectedIndex,this.renderSuggestions());break;case"ArrowUp":e.preventDefault(),this.suggestions.length>0&&(this.selectedIndex=this.selectedIndex>0?this.selectedIndex-1:-1,this.renderSuggestions());break;case"Enter":e.preventDefault(),this.suggestions.length>0&&this.selectedIndex>=0&&this.selectedIndex<this.suggestions.length?this.selectSuggestion(this.suggestions[this.selectedIndex].query):this.performSearch();break;case"Escape":this.isFocused=!1,this.selectedIndex=-1,this.updateSuggestionsVisibility(),this.input.blur()}}selectSuggestion(e){this.input.value=e,this.selectedIndex=-1,this.isFocused=!1,this.updateSuggestionsVisibility(),this.input.blur(),this.options.onSuggestionSelect&&this.options.onSuggestionSelect(e),this.performSearch()}async fetchRichSuggestions(e){try{c("SearchBar: Fetching rich suggestions via client.getSuggestions",{query:e});const t=await this.client.getSuggestions(e,{include_dropdown_recommendations:!0,hitsPerPage:this.options.maxSuggestions,returnFullResponse:!0}),n=t.suggestions||[],s=t.extensions,i=t.raw||{},r={status:"success",data:{hits:n,nbHits:n.length,page:i.page||0,hitsPerPage:i.hitsPerPage||this.options.maxSuggestions,processingTimeMS:i.processingTimeMS||0,query:e,indexUsed:i.indexUsed||"",parsedQuery:i.parsedQuery||e,dropdown_recommendations:s?{trending_searches:s.trending_searches,trending_products:s.trending_products,popular_brands:s.popular_brands,processing_time_ms:s.processing_time_ms||0,cached_at:s.cached_at}:void 0},timestamp:i.timestamp||(new Date).toISOString(),version:i.version||""};this.richSuggestionsData=r,this.suggestions=n.map(e=>({query:e.query,count:e.popularity,metadata:e})),c("SearchBar: Rich suggestions loaded",{query:e,suggestionsCount:this.suggestions.length,hasTrendingSearches:!!r.data.dropdown_recommendations?.trending_searches?.length,hasTrendingProducts:!!r.data.dropdown_recommendations?.trending_products?.length,hasPopularBrands:!!r.data.dropdown_recommendations?.popular_brands?.length})}catch(t){const n=t instanceof Error?t:new Error(String(t));g("SearchBar: Failed to fetch rich suggestions, falling back to basic",{error:n.message,query:e}),await this.fallbackToBasicSuggestions(e)}}async fallbackToBasicSuggestions(e){try{const t=await this.client.getSuggestions(e,this.options.maxSuggestions),n=Array.isArray(t)?t:[];this.suggestions=n.map(e=>{const t=e.query??e.text??e,n=void 0!==e.popularity?e.popularity:void 0!==e.count?e.count:void 0;return{query:"string"==typeof t?t:String(t),count:"number"==typeof n?n:void 0,metadata:e}}),this.richSuggestionsData=null}catch(e){g("SearchBar: Fallback suggestions also failed",e),this.suggestions=[],this.richSuggestionsData=null}}async performSearch(){const e=this.input.value.trim();c("SearchBar: Setting query in state manager",{query:e}),this.provider.stateManager.setQuery(e)}renderSuggestions(){this.suggestionsContainer.innerHTML="";const e=this.richSuggestionsData?.data?.dropdown_recommendations,t=e?this.richSuggestionsData.data.dropdown_recommendations:null;console.log("🎨 SearchBar: renderSuggestions called",{hasRichData:e,recommendationsKeys:t?Object.keys(t):[],trendingSearchesCount:t?.trending_searches?.length||0,trendingProductsCount:t?.trending_products?.length||0,popularBrandsCount:t?.popular_brands?.length||0,suggestionsCount:this.suggestions.length});const n=this.suggestions.slice(0,this.options.maxSuggestions);if(n.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const t=document.createElement("div");t.style.cssText=this.getSectionTitleStyle(),t.textContent="Suggestions",e.appendChild(t);const s=document.createElement("div");s.style.cssText=this.getSuggestionsListStyle(),n.forEach((e,t)=>{const n=document.createElement("div");n.style.cssText=this.getSuggestionItemStyle(t===this.selectedIndex);const i=document.createElement("span");if(i.textContent=e.query,n.appendChild(i),void 0!==e.count){const t=document.createElement("span");t.textContent=` (${e.count})`,t.style.cssText=this.getCountStyle(),n.appendChild(t)}n.addEventListener("mousedown",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),n.addEventListener("click",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),s.appendChild(n)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}if(t?.trending_searches&&t.trending_searches.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const n=document.createElement("div");n.style.cssText=this.getSectionTitleStyle(),n.textContent="Trending Searches",e.appendChild(n);const s=document.createElement("div");s.style.cssText=this.getSuggestionsListStyle(),t.trending_searches.forEach(e=>{const t=document.createElement("div");t.style.cssText=this.getSuggestionItemStyle(!1);const n=document.createElement("span");if(n.textContent=e.query,t.appendChild(n),void 0!==e.searches){const n=document.createElement("span");n.textContent=` (${e.searches})`,n.style.cssText=this.getCountStyle(),t.appendChild(n)}t.addEventListener("mousedown",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),t.addEventListener("click",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),s.appendChild(t)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}if(t?.trending_products&&t.trending_products.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const n=document.createElement("div");n.style.cssText=this.getSectionTitleStyle(),n.textContent="Trending Products",e.appendChild(n);const s=document.createElement("div");s.style.cssText=this.getProductsGridStyle(),t.trending_products.forEach(e=>{const t=document.createElement("div");if(t.style.cssText=this.getProductCardStyle(),e.image){const n=document.createElement("img");n.src=e.image,n.alt=e.title,n.style.cssText=this.getProductImageStyle(),n.onerror=()=>{n.style.display="none"},t.appendChild(n)}const n=document.createElement("div");n.style.cssText=this.getProductInfoStyle();const i=document.createElement("div");if(i.style.cssText=this.getProductTitleStyle(),i.textContent=e.title,n.appendChild(i),void 0!==e.price){const t=document.createElement("div");t.style.cssText=this.getProductPriceStyle();const s=e.currency||"$";t.textContent=`${s}${e.price}`,n.appendChild(t)}t.appendChild(n),t.addEventListener("mousedown",t=>{t.preventDefault(),this.options.onProductClick?this.options.onProductClick(e.id,e):e.url&&(window.location.href=e.url)}),t.addEventListener("click",t=>{t.preventDefault(),this.options.onProductClick?this.options.onProductClick(e.id,e):e.url&&(window.location.href=e.url)}),s.appendChild(t)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}if(t?.popular_brands&&t.popular_brands.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const n=document.createElement("div");n.style.cssText=this.getSectionTitleStyle(),n.textContent="Popular Brands",e.appendChild(n);const s=document.createElement("div");s.style.cssText=this.getBrandsListStyle(),t.popular_brands.forEach(e=>{const t=document.createElement("div");if(t.style.cssText=this.getBrandItemStyle(),e.logo){const n=document.createElement("img");n.src=e.logo,n.alt=e.name,n.style.cssText=this.getBrandLogoStyle(),n.onerror=()=>{n.style.display="none";const s=document.createElement("span");s.textContent=e.name,s.style.cssText=this.getBrandNameStyle(),t.appendChild(s)},t.appendChild(n)}else{const n=document.createElement("span");n.textContent=e.name,n.style.cssText=this.getBrandNameStyle(),t.appendChild(n)}t.addEventListener("mousedown",t=>{t.preventDefault(),this.options.onBrandClick?this.options.onBrandClick(e.name,e):this.selectSuggestion(e.name)}),t.addEventListener("click",t=>{t.preventDefault(),this.options.onBrandClick?this.options.onBrandClick(e.name,e):this.selectSuggestion(e.name)}),s.appendChild(t)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}this.updateSuggestionsVisibility()}updateSuggestionsVisibility(){const e=this.richSuggestionsData?.data?.dropdown_recommendations,t=(e?.trending_products?.length??0)>0,n=(e?.trending_searches?.length??0)>0,s=(e?.popular_brands?.length??0)>0,i=this.suggestions.length>0||t||n||s,r=this.input.value.length,o=0===r&&(t||n||s),a=r>=this.options.minQueryLength||this.options.enableRichSuggestions&&o,l=this.isFocused&&this.options.showSuggestions&&a&&i;console.log("👁️ updateSuggestionsVisibility",{isFocused:this.isFocused,hasAnyContent:i,suggestionsCount:this.suggestions.length,hasTrendingProducts:t,hasPopularBrands:s,queryLength:r,isEmptyWithRichData:o,canShow:a,shouldShow:l}),this.suggestionsContainer.style.display=l?"block":"none"}getInputStyle(){const e=this.provider.theme;return`\n flex: 1;\n padding: ${e.spacing.medium};\n font-size: ${e.typography.fontSize.medium};\n font-family: ${e.typography.fontFamily};\n background-color: ${e.colors.background};\n color: ${e.colors.text};\n border: 1px solid ${e.colors.border};\n border-radius: ${"string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium};\n outline: none;\n `}getResponseTimeStyle(){const e=this.provider.theme;return`\n margin-left: ${e.spacing.small};\n font-size: ${e.typography.fontSize.small};\n color: ${e.colors.text};\n opacity: 0.7;\n white-space: nowrap;\n `}getSuggestionsContainerStyle(){const e=this.provider.theme;return`\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n margin-top: ${e.spacing.small};\n background-color: ${e.colors.background};\n border: 1px solid ${e.colors.border};\n border-radius: ${"string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium};\n box-shadow: ${e.shadows.medium};\n max-height: 600px;\n overflow-y: auto;\n z-index: 1000;\n width: 100%;\n `}getSuggestionItemStyle(e){const t=this.provider.theme;return`\n padding: ${t.spacing.medium};\n cursor: pointer;\n background-color: ${e?t.colors.hover:"transparent"};\n color: ${t.colors.text};\n font-family: ${t.typography.fontFamily};\n transition: ${t.transitions?.fast||"150ms ease-in-out"};\n `}getSectionStyle(){const e=this.provider.theme;return`\n padding: ${e.spacing.large||"1.5rem"} ${e.spacing.medium};\n border-bottom: 1px solid ${e.colors.border};\n `}getSectionTitleStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.small};\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n color: ${e.colors.textSecondary||e.colors.text};\n opacity: 0.7;\n margin-bottom: ${e.spacing.medium};\n `}getSuggestionsListStyle(){return"\n display: flex;\n flex-direction: column;\n "}getCountStyle(){const e=this.provider.theme;return`\n opacity: 0.6;\n margin-left: ${e.spacing.small};\n font-size: ${e.typography.fontSize.small};\n `}getProductsGridStyle(){return`\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));\n gap: ${this.provider.theme.spacing.medium};\n max-height: 300px;\n overflow-y: auto;\n `}getProductCardStyle(){const e=this.provider.theme,t="string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium;return`\n display: flex;\n flex-direction: column;\n cursor: pointer;\n border: 1px solid ${e.colors.border};\n border-radius: ${t};\n overflow: hidden;\n transition: ${e.transitions?.fast||"150ms ease-in-out"};\n background-color: ${e.colors.background};\n `}getProductImageStyle(){return"\n width: 100%;\n height: 120px;\n object-fit: cover;\n background-color: #f0f0f0;\n "}getProductInfoStyle(){const e=this.provider.theme;return`\n padding: ${e.spacing.small} ${e.spacing.medium};\n display: flex;\n flex-direction: column;\n gap: ${e.spacing.xsmall??e.spacing.small??"0.25rem"};\n `}getProductTitleStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.small};\n font-weight: 500;\n color: ${e.colors.text};\n line-height: 1.4;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n `}getProductPriceStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.medium};\n font-weight: 600;\n color: ${e.colors.primary||e.colors.text};\n `}getBrandsListStyle(){return`\n display: flex;\n flex-wrap: wrap;\n gap: ${this.provider.theme.spacing.medium};\n max-height: 200px;\n overflow-y: auto;\n `}getBrandItemStyle(){const e=this.provider.theme,t="string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium;return`\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n padding: ${e.spacing.small};\n border: 1px solid ${e.colors.border};\n border-radius: ${t};\n transition: ${e.transitions?.fast||"150ms ease-in-out"};\n background-color: ${e.colors.background};\n min-width: 80px;\n min-height: 60px;\n `}getBrandLogoStyle(){return"\n max-width: 60px;\n max-height: 40px;\n object-fit: contain;\n "}getBrandNameStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.small};\n font-weight: 500;\n color: ${e.colors.text};\n text-align: center;\n `}async search(e){void 0!==e&&(this.input.value=e),await this.performSearch()}destroy(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.container.innerHTML=""}},e.SearchLayout=class{constructor(e,t){this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("SearchLayout: container element not found");throw g("SearchLayout: Initialization failed",{error:e.message}),e}this.container=n,this.options={sidebarWidth:t.sidebarWidth||"300px",showSidebarOnMobile:t.showSidebarOnMobile||!1,sidebar:t.sidebar,header:t.header,footer:t.footer},this.render()}render(){if(this.container.innerHTML="",this.container.style.cssText=this.getContainerStyle(),this.options.header&&(this.headerEl="string"==typeof this.options.header?document.querySelector(this.options.header):this.options.header,this.headerEl)){const e=document.createElement("header");e.style.cssText=this.getHeaderStyle(),e.appendChild(this.headerEl.cloneNode(!0)),this.container.appendChild(e)}const e=document.createElement("div");if(e.style.cssText=this.getContentStyle(),this.options.sidebar&&(this.sidebarEl="string"==typeof this.options.sidebar?document.querySelector(this.options.sidebar):this.options.sidebar,this.sidebarEl)){const t=document.createElement("aside");t.style.cssText=this.getSidebarStyle(),t.className=this.getSidebarClass();const n=this.sidebarEl.cloneNode(!0);t.appendChild(n),e.appendChild(t)}if(this.mainEl=document.createElement("main"),this.mainEl.style.cssText=this.getMainStyle(),e.appendChild(this.mainEl),this.container.appendChild(e),this.options.footer&&(this.footerEl="string"==typeof this.options.footer?document.querySelector(this.options.footer):this.options.footer,this.footerEl)){const e=document.createElement("footer");e.style.cssText=this.getFooterStyle(),e.appendChild(this.footerEl.cloneNode(!0)),this.container.appendChild(e)}if(!this.options.showSidebarOnMobile){const e=document.createElement("style");e.textContent="\n @media (max-width: 768px) {\n .search-layout-sidebar-hidden-mobile {\n display: none;\n }\n }\n ",document.head.appendChild(e)}}getMainElement(){return this.mainEl}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n background-color: ${this.theme.colors.background};\n `}getHeaderStyle(){return`\n padding: ${this.theme.spacing.medium};\n border-bottom: 1px solid ${this.theme.colors.border};\n background-color: ${this.theme.colors.background};\n `}getContentStyle(){return`\n display: flex;\n flex: 1;\n gap: ${this.theme.spacing.large};\n padding: ${this.theme.spacing.medium};\n `}getSidebarStyle(){return`\n width: ${this.options.sidebarWidth};\n min-width: ${this.options.sidebarWidth};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n `}getSidebarClass(){return this.options.showSidebarOnMobile?"":"search-layout-sidebar-hidden-mobile"}getMainStyle(){return"\n flex: 1;\n min-width: 0;\n "}getFooterStyle(){return`\n padding: ${this.theme.spacing.medium};\n border-top: 1px solid ${this.theme.colors.border};\n background-color: ${this.theme.colors.background};\n `}},e.SearchManager=class{constructor(e){this.state={results:null,loading:!1,error:null},this.listeners=[],this.client=e.client,this.theme=e.theme||this.getDefaultTheme()}async search(e){this.setState({loading:!0,error:null});try{const{q:t,...n}=e,s="string"==typeof t?t:"",i=await this.client.search(s,n);return this.setState({results:i,loading:!1,error:null}),i}catch(e){const t=e instanceof Error?e:new Error(String(e));return this.setState({results:null,loading:!1,error:t}),null}}clearResults(){this.setState({results:null,error:null})}getState(){return{...this.state}}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}getTheme(){return this.theme}setState(e){this.state={...this.state,...e},this.listeners.forEach(e=>e(this.state))}getDefaultTheme(){return{colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",text:"#212529",border:"#dee2e6",hover:"#f8f9fa",focus:"#007bff",error:"#dc3545"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.25rem"}},spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},borderRadius:{small:"0.25rem",medium:"0.375rem",large:"0.5rem"},shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.12)",medium:"0 3px 6px rgba(0, 0, 0, 0.16)",large:"0 10px 20px rgba(0, 0, 0, 0.19)"}}}},e.SearchProvider=S,e.SearchResults=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("SearchResults: container element not found");this.container=n,this.options={viewMode:t.viewMode||"list",fieldMapping:t.fieldMapping||{},itemsPerPage:t.itemsPerPage||10,results:t.results,loading:t.loading,error:t.error,onResultClick:t.onResultClick,renderResult:t.renderResult,renderEmpty:t.renderEmpty,renderError:t.renderError},this.container.addEventListener("click",async e=>{const t=e.target,n=t.hasAttribute("data-result-id")?t:t.closest("[data-result-id]");if(n){e.preventDefault(),e.stopPropagation();const s=n.getAttribute("data-result-id"),i=n.getAttribute("data-result-index"),r=i?parseInt(i,10):-1;if(console.log("🔵 SearchResults: Result clicked via delegation",{resultId:s,resultIndex:r,target:t.tagName,resultElement:n}),s&&r>=0){const e=this.extractResults()[r];if(e){const t=this.extractFields(e);if(this.provider.enableAnalytics)try{const e=this.provider.stateManager.getResults(),n=this.provider.stateManager.getState(),i=(n.currentPage-1)*n.itemsPerPage+r+1,o=e?.context||(e?{query:n.query,filters:n.refinements.length>0?n.refinements.map(e=>`${e.field}:${e.value}`).join(" && "):void 0,page:n.currentPage,sortBy:n.sortBy}:void 0);console.log("🔵 SearchResults: Tracking analytics event",{resultId:s,resultIndex:r,absolutePosition:i,currentPage:n.currentPage,itemsPerPage:n.itemsPerPage,hasContext:!!o,searchContext:o}),await this.provider.client.trackEvent({event_name:"product_click",clicked_item_id:s,metadata:{result:t,position:i}},o),console.log("🟢 SearchResults: Analytics event tracked successfully",{resultId:s,position:i})}catch(e){const t=e instanceof Error?e:new Error(String(e));g("SearchResults: Error tracking analytics event",{resultId:s,error:t.message})}if(this.options.onResultClick)try{console.log("🔵 SearchResults: Calling onResultClick callback",{resultId:s,resultIndex:r,extractedResult:t}),this.options.onResultClick(t,r)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("SearchResults: Error in onResultClick callback",{resultId:s,resultIndex:r,error:t.message})}}}}},{passive:!1}),console.log("🔵 SearchResults: Event delegation listener attached to container",{container:this.container}),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{this.options.results=e.results,this.options.loading=e.loading,this.options.error=e.error,this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.loading&&(this.options.loading=e.loading),void 0!==e.error&&(this.options.error=e.error);const t=this.extractResults().length;c("SearchResults: Updating and re-rendering",{hasResults:!!this.options.results,loading:this.options.loading,hasError:!!this.options.error,resultsCount:t,providedResults:void 0!==e.results,providedLoading:void 0!==e.loading,providedError:void 0!==e.error}),this.render()}render(){if(this.container.innerHTML="",c("SearchResults: Rendering",{hasResults:!!this.options.results,loading:this.options.loading,hasError:!!this.options.error}),this.options.error){const e=this.options.renderError?this.options.renderError(this.options.error):this.renderDefaultError(this.options.error);return void this.container.appendChild(e)}const e=this.extractResults();if(0===e.length){const e=this.options.renderEmpty?this.options.renderEmpty():this.renderDefaultEmpty();return void this.container.appendChild(e)}if("card"===this.options.viewMode||"grid"===this.options.viewMode){const t=document.createElement("div");t.style.cssText=this.getGridContainerStyle(),e.forEach((e,n)=>{const s=this.options.renderResult?this.options.renderResult(this.extractFields(e),n):this.renderDefaultResult(this.extractFields(e),n);t.appendChild(s)}),this.container.appendChild(t)}else e.forEach((e,t)=>{const n=this.options.renderResult?this.options.renderResult(this.extractFields(e),t):this.renderDefaultResult(this.extractFields(e),t);this.container.appendChild(n)})}extractResults(){if(!this.options.results)return c("SearchResults: No results to extract"),[];let e=[];if(Array.isArray(this.options.results))e=this.options.results;else{const t=this.options.results;if(t.results&&Array.isArray(t.results))e=t.results;else if(t.data){const n=t.data;Array.isArray(n)?e=n:n.results&&Array.isArray(n.results)&&(e=n.results)}}return c("SearchResults: Extracted results",{count:e.length,viewMode:this.options.viewMode}),e}extractFields(e){try{const t=this.options.fieldMapping;return{id:r(e,t.id)||String(e.id||""),title:r(e,t.title)||r(e,t.primaryText)||"Untitled",description:r(e,t.description)||r(e,t.secondaryText),image:r(e,t.image)||r(e,t.imageUrl),price:t.price?i(r(e,t.price)):void 0,url:r(e,t.url),metadata:e}}catch(t){const n=t instanceof Error?t:new Error(String(t));return u("SearchResults: Error extracting fields from result",{error:n.message,itemId:e?.id||"unknown"}),{id:String(e?.id||""),title:"Error loading result",metadata:e}}}renderDefaultError(e){const t=document.createElement("div");return t.style.cssText=this.getErrorStyle(),t.textContent=`Error: ${e.message}`,t}renderDefaultEmpty(){const e=document.createElement("div");return e.style.cssText=this.getEmptyStyle(),e.textContent="No results found",e}renderDefaultResult(e,t){const n=document.createElement("div");return n.style.cssText=this.getResultStyle(t),n.setAttribute("data-result-id",e.id),n.setAttribute("data-result-index",String(t)),this.options.onResultClick&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),console.log("SearchResults: Result element created",{resultId:e.id,index:t,element:n,hasOnResultClick:!!this.options.onResultClick}),n.addEventListener("keydown",e=>{if("Enter"===e.key||" "===e.key){e.preventDefault(),e.stopPropagation();const t=new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window});n.dispatchEvent(t)}})),"card"===this.options.viewMode||"grid"===this.options.viewMode?this.renderCardResult(n,e):this.renderListResult(n,e),n}renderCardResult(e,t){if(t.image){const n=document.createElement("div");n.style.cssText=this.getImageContainerStyle();const s=document.createElement("img");s.src=t.image,s.alt=t.title,s.style.cssText=this.getImageStyle(),n.appendChild(s),e.appendChild(n)}const n=document.createElement("div");if(n.style.cssText=this.getCardContentStyle(),t.title){const e=document.createElement("h3");e.style.cssText=this.getTitleStyle(),e.textContent=t.title,n.appendChild(e)}if(t.description){const e=document.createElement("p");e.style.cssText=this.getDescriptionStyle(),e.textContent=t.description,n.appendChild(e)}if(t.price){const e=document.createElement("div");e.style.cssText=this.getPriceStyle(),e.textContent=t.price,n.appendChild(e)}e.appendChild(n)}renderListResult(e,t){if(t.image){const n=document.createElement("img");n.src=t.image,n.alt=t.title,n.style.cssText=this.getListImageStyle(),e.appendChild(n)}const n=document.createElement("div");if(n.style.cssText="flex: 1; min-width: 0;",t.title){const e=document.createElement("h3");e.style.cssText=this.getTitleStyle(),e.textContent=t.title,n.appendChild(e)}if(t.description){const e=document.createElement("p");e.style.cssText=this.getDescriptionStyle(),e.textContent=t.description,n.appendChild(e)}if(t.price){const e=document.createElement("div");e.style.cssText=this.getPriceStyle(),e.textContent=t.price,n.appendChild(e)}e.appendChild(n)}get theme(){return this.provider.theme}getErrorStyle(){return`\n padding: ${this.theme.spacing.large};\n text-align: center;\n color: ${this.theme.colors.error};\n `}getEmptyStyle(){return`\n padding: ${this.theme.spacing.large};\n text-align: center;\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n `}getGridContainerStyle(){return`\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));\n gap: ${this.theme.spacing.medium};\n width: 100%;\n `}getResultStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium,n=this.theme.transitions?.normal||"250ms ease-in-out";return"list"===this.options.viewMode?`\n padding: ${this.theme.spacing.medium};\n border-bottom: 1px solid ${this.theme.colors.border};\n border-radius: 0;\n margin-bottom: 0;\n transition: ${n};\n background-color: ${this.theme.colors.background};\n display: flex;\n align-items: flex-start;\n gap: ${this.theme.spacing.medium};\n `:`\n padding: 0;\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${t};\n box-shadow: ${this.theme.shadows.small};\n transition: ${n};\n background-color: ${this.theme.colors.background};\n display: flex;\n flex-direction: column;\n overflow: hidden;\n height: 100%;\n `}getImageContainerStyle(){return`\n width: 100%;\n aspect-ratio: ${"grid"===this.options.viewMode?"1/1":"16/9"};\n overflow: hidden;\n background-color: ${this.theme.colors.hover};\n flex-shrink: 0;\n `}getImageStyle(){return"\n width: 100%;\n height: 100%;\n object-fit: cover;\n "}getCardContentStyle(){return`\n padding: ${this.theme.spacing.medium};\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n `}getListContentStyle(){return`\n display: flex;\n align-items: flex-start;\n gap: ${this.theme.spacing.medium};\n flex: 1;\n min-width: 0;\n `}getListImageStyle(){return`\n width: 100px;\n height: 100px;\n object-fit: cover;\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium};\n flex-shrink: 0;\n `}getTitleStyle(){return`\n font-size: ${this.theme.typography.fontSize.large};\n font-weight: bold;\n margin: 0;\n margin-bottom: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getDescriptionStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n margin: 0;\n margin-bottom: ${this.theme.spacing.small};\n opacity: 0.8;\n `}getPriceStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: bold;\n color: ${this.theme.colors.primary};\n margin-top: auto;\n `}},e.SortBy=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("SortBy: container element not found");throw g("SortBy: Initialization failed",{error:e.message}),e}this.container=n,this.currentValue=t.value||t.options[0]?.value||"",this.options={options:t.options,label:t.label,onSortChange:t.onSortChange},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.sortBy&&e.sortBy!==this.currentValue&&(this.currentValue=e.sortBy,this.render())}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}update(e){void 0!==e.value&&(this.currentValue=e.value,this.render())}render(){this.container.innerHTML="";const e=document.createElement("div");if(e.style.cssText=this.getContainerStyle(),this.options.label){const t=document.createElement("label");t.textContent=this.options.label,t.style.cssText=this.getLabelStyle(),e.appendChild(t)}const t=document.createElement("select");t.value=this.currentValue,t.style.cssText=this.getSelectStyle(),t.setAttribute("aria-label","Sort results"),t.addEventListener("change",e=>{const t=e.target;if(this.currentValue=t.value,c("SortBy: Sort option changed",{value:t.value}),this.provider.stateManager.setSortBy(t.value),this.options.onSortChange)try{this.options.onSortChange(t.value)}catch(e){const n=e instanceof Error?e:new Error(String(e));g("SortBy: Error in onSortChange callback",{value:t.value,error:n.message})}}),this.options.options.forEach(e=>{const n=document.createElement("option");n.value=e.value,n.textContent=e.label,t.appendChild(n)}),e.appendChild(t),this.container.appendChild(e)}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n `}getLabelStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n `}getSelectStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n cursor: pointer;\n outline: none;\n `}},e.Stats=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("Stats: container element not found");throw g("Stats: Initialization failed",{error:e.message}),e}this.container=n,this.options={showProcessingTime:t.showProcessingTime||!1,results:t.results,loading:t.loading,labels:t.labels},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{this.options.results=e.results,this.options.loading=e.loading,this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.loading&&(this.options.loading=e.loading),this.render()}render(){this.container.innerHTML="";const e=this.getTotalResults();if(null===e)return;const t=document.createElement("div");t.style.cssText=this.getContainerStyle();const n=this.getResultsLabel(e),s=document.createElement("span");if(s.textContent=n,s.style.cssText=this.getResultsStyle(),t.appendChild(s),this.options.showProcessingTime){const e=this.getProcessingTime();if(null!==e){const n=this.getProcessingTimeLabel(e),s=document.createElement("span");s.textContent=n,s.style.cssText=this.getTimeStyle(),t.appendChild(s)}}this.container.appendChild(t)}getTotalResults(){return this.options.results?"number"==typeof this.options.results.totalResults?this.options.results.totalResults:"number"==typeof this.options.results.total?this.options.results.total:this.options.results.results&&Array.isArray(this.options.results.results)?(u("Stats: Using results array length as total (totalResults not found)",{resultsLength:this.options.results.results.length,responseKeys:Object.keys(this.options.results)}),this.options.results.results.length):null:null}getProcessingTime(){if(!this.options.results)return null;const e=this.options.results.processingTimeMs;return"number"==typeof e?e:null}getResultsLabel(e){return this.options.labels?.resultsFound?this.options.labels.resultsFound(e):`${e} result${1!==e?"s":""} found`}getProcessingTimeLabel(e){return this.options.labels?.processingTime?this.options.labels.processingTime(e):` (${e}ms)`}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n `}getResultsStyle(){return`\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n `}getTimeStyle(){return`\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n opacity: 0.7;\n `}},e.createRatingDisplay=function(e,t){return new s(e,t)},e.createTheme=y,e.darkTheme={colors:{primary:"#0d6efd",secondary:"#6c757d",background:"#1a1a1a",text:"#ffffff",border:"#333333",hover:"#2a2a2a",focus:"#0d6efd",error:"#dc3545"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.25rem"}},spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},borderRadius:"0.25rem",shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.5), 0 1px 2px rgba(0, 0, 0, 0.7)",medium:"0 3px 6px rgba(0, 0, 0, 0.6), 0 3px 6px rgba(0, 0, 0, 0.8)",large:"0 10px 20px rgba(0, 0, 0, 0.7), 0 6px 6px rgba(0, 0, 0, 0.9)"}},e.defaultTheme=f,e.getHighlightedValue=p,e.getSnippetedValue=function(e){const{attribute:t,hit:n,preTag:s="<mark>",postTag:i="</mark>",fallback:r,maxLength:o=100,ellipsis:a="..."}=e,l=n._snippetResult?.[t]?.value||n.snippet_result?.[t]?.value||n._snippet?.[t]||n.snippet?.[t];let h="";if(h=l?l.replace(/<em>/g,s).replace(/<\/em>/g,i).replace(/<mark>/g,s).replace(/<\/mark>/g,i):p(e),h.length>o){const e=h.substring(0,o),t=e.lastIndexOf(" ");return t>.7*o?e.substring(0,t)+a:e+a}return h},e.highlightQuery=function(e,t,n={}){const{preTag:s="<mark>",postTag:i="</mark>",caseSensitive:r=!1}=n;if(!t||!e)return e;const o=r?"g":"gi",a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${a})`,o);return e.replace(l,`${s}$1${i}`)},e.mergeThemes=(e,...t)=>t.reduce((e,t)=>({colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography,fontSize:{...e.typography?.fontSize,...t.typography?.fontSize}},spacing:{...e.spacing,...t.spacing},borderRadius:t.borderRadius??e.borderRadius,shadows:{...e.shadows,...t.shadows},transitions:{...e.transitions,...t.transitions},breakpoints:{...e.breakpoints,...t.breakpoints},zIndex:{...e.zIndex,...t.zIndex}}),e),e.minimalTheme={colors:{primary:"#000000",secondary:"#666666",background:"#ffffff",text:"#000000",border:"#e0e0e0",hover:"#f5f5f5",focus:"#000000",error:"#cc0000"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.125rem"}},spacing:{small:"0.5rem",medium:"0.75rem",large:"1rem"},borderRadius:"0",shadows:{small:"none",medium:"none",large:"none"}},e.parseHighlightedParts=function(e,t="<mark>",n="</mark>"){const s=[];let i=e;for(;i.length>0;){const e=i.indexOf(t);if(-1===e){i.length>0&&s.push({value:i,isHighlighted:!1});break}e>0&&s.push({value:i.substring(0,e),isHighlighted:!1});const r=i.substring(e+t.length),o=r.indexOf(n);if(-1===o){s.push({value:i.substring(e),isHighlighted:!1});break}s.push({value:r.substring(0,o),isHighlighted:!0}),i=r.substring(o+n.length)}return s},e.parseQueryHighlightParts=function(e,t,n=!1){if(!t||!e)return[{value:e,isHighlighted:!1}];const s=[],i=n?"g":"gi",r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(r,i);let a,l=0;for(;null!==(a=o.exec(e));)a.index>l&&s.push({value:e.substring(l,a.index),isHighlighted:!1}),s.push({value:a[0],isHighlighted:!0}),l=o.lastIndex;return l<e.length&&s.push({value:e.substring(l),isHighlighted:!1}),s.length>0?s:[{value:e,isHighlighted:!1}]},e.stripHighlightTags=function(e){return e.replace(/<mark>/g,"").replace(/<\/mark>/g,"").replace(/<em>/g,"").replace(/<\/em>/g,"")}});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SeekoraVanilla={})}(this,function(e){"use strict";const t={small:14,medium:18,large:24},n={small:"0.75rem",medium:"0.875rem",large:"1rem"};class s{constructor(e,t){if(this.hoverRating=null,this.container="string"==typeof e?document.querySelector(e):e,!this.container)throw new Error("RatingDisplay: Container element not found");this.options={variant:"compact",size:"medium",maxRating:5,showNumeric:!1,showHalfStars:!0,interactive:!1,starColor:"#f59e0b",emptyStarColor:"#d1d5db",textColor:"var(--seekora-text-secondary, #6b7280)",showReviewCount:!0,onRatingChange:()=>{},reviewCountFormat:this.defaultReviewCountFormat,className:"",...t},this.render()}defaultReviewCountFormat(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString()}createStarSVG(e,t,n){const{starColor:s,emptyStarColor:i}=this.options;return t?`\n <svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <defs>\n <linearGradient id="half-fill-${Math.random()}">\n <stop offset="50%" stop-color="${s}" />\n <stop offset="50%" stop-color="${i}" />\n </linearGradient>\n </defs>\n <path\n d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"\n fill="url(#half-fill-${Math.random()})"\n stroke="${s}"\n stroke-width="1"\n />\n </svg>\n `:`\n <svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="${e?s:"none"}" xmlns="http://www.w3.org/2000/svg">\n <path\n d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"\n stroke="${e?s:i}"\n stroke-width="1.5"\n stroke-linecap="round"\n stroke-linejoin="round"\n />\n </svg>\n `}renderStars(){const{rating:e,maxRating:n,showHalfStars:s,interactive:i}=this.options,r=i&&null!==this.hoverRating?this.hoverRating:e,o=t[this.options.size];let a="";for(let e=1;e<=n;e++){const t=e<=Math.floor(r),n=s&&e===Math.ceil(r)&&r%1>=.25&&r%1<.75;a+=`\n <span\n class="${`seekora-rating-star ${t?"seekora-rating-star--filled":"seekora-rating-star--empty"} ${i?"seekora-rating-star--interactive":""}`}"\n data-rating="${e}"\n style="display: inline-block; width: ${o}px; height: ${o}px; cursor: ${i?"pointer":"default"};"\n >\n ${this.createStarSVG(t,n,o)}\n </span>\n `}return`<div style="display: inline-flex; align-items: center; gap: 2px;">${a}</div>`}render(){const{variant:e,rating:t,reviewCount:s,showNumeric:i,showReviewCount:r,textColor:o,maxRating:a,className:l}=this.options,h=n[this.options.size],c=Math.max(0,Math.min(a,t));let d="";"stars-only"===e?d=`\n <div class="seekora-rating-display seekora-rating-display--stars-only ${l}"\n style="display: inline-flex; align-items: center; gap: 2px;">\n ${this.renderStars()}\n </div>\n `:"compact"===e?d=`\n <div class="seekora-rating-display seekora-rating-display--compact ${l}"\n style="display: inline-flex; align-items: center; gap: 4px; font-size: ${h};">\n ${this.renderStars()}\n ${i?`<span class="seekora-rating-numeric" style="font-weight: 600; color: ${o};">${c.toFixed(1)}</span>`:""}\n ${r&&null!=s&&s>0?`<span class="seekora-rating-review-count" style="color: ${o};">(${this.options.reviewCountFormat(s)})</span>`:""}\n </div>\n `:"inline"===e?d=`\n <div class="seekora-rating-display seekora-rating-display--inline ${l}"\n style="display: inline-flex; align-items: center; gap: 6px; font-size: ${h};">\n <span class="seekora-rating-numeric" style="font-weight: 600; color: var(--seekora-text-primary, #111827);">${c.toFixed(1)}</span>\n ${this.renderStars()}\n ${r&&null!=s&&s>0?`<span class="seekora-rating-review-count" style="color: ${o};">(${this.options.reviewCountFormat(s)})</span>`:""}\n </div>\n `:"full"===e&&(d=`\n <div class="seekora-rating-display seekora-rating-display--full ${l}"\n style="display: flex; flex-direction: column; gap: 4px; font-size: ${h};">\n <div style="display: flex; align-items: center; gap: 6px;">\n ${this.renderStars()}\n <span class="seekora-rating-numeric" style="font-weight: 600; color: var(--seekora-text-primary, #111827);">${c.toFixed(1)}</span>\n <span class="seekora-rating-max" style="color: ${o};">/ ${a}</span>\n </div>\n ${r&&null!=s&&s>0?`\n <span class="seekora-rating-review-text" style="font-size: 0.875em; color: ${o};">\n Based on ${this.options.reviewCountFormat(s)} ${1===s?"review":"reviews"}\n </span>\n `:""}\n </div>\n `),this.container.innerHTML=d,this.options.interactive&&this.attachEventListeners()}attachEventListeners(){this.container.querySelectorAll(".seekora-rating-star").forEach(e=>{e.addEventListener("mouseenter",()=>{const t=parseInt(e.dataset.rating||"0");this.hoverRating=t,this.render()}),e.addEventListener("click",()=>{const t=parseInt(e.dataset.rating||"0");this.hoverRating=null,this.options.onRatingChange(t),this.render()})}),this.container.addEventListener("mouseleave",()=>{this.hoverRating=null,this.render()})}update(e){this.options={...this.options,...e},this.render()}destroy(){this.container.innerHTML=""}}const i=(e,t="₹")=>{if(null!=e){if("number"==typeof e)return`${t}${e}`;if("string"==typeof e){const n=parseFloat(e);return isNaN(n)?e:`${t}${n}`}return String(e)}},r=(e,t)=>{if(t)return((e,t)=>{if(t)return t.split(".").reduce((e,t)=>e?.[t],e)})(e,t)};var o;!function(e){e[e.VERBOSE=0]="VERBOSE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT"}(o||(o={}));class a{constructor(e={}){this.level=e.level??this.getDefaultLevel(),this.prefix=e.prefix??"[Seekora UI SDK]",this.enableTimestamp=e.enableTimestamp??!1}getDefaultLevel(){switch(void 0){case"VERBOSE":return o.VERBOSE;case"INFO":return o.INFO;case"WARN":return o.WARN;case"ERROR":return o.ERROR;case"SILENT":return o.SILENT}return"undefined"!=typeof window&&window.__SEEKORA_DEBUG__?o.VERBOSE:o.INFO}formatMessage(e,...t){const n=[];return this.enableTimestamp&&n.push(`[${(new Date).toISOString()}]`),n.push(this.prefix,`[${e}]`),[...n,...t]}verbose(...e){this.level<=o.VERBOSE&&console.log(...this.formatMessage("VERBOSE",...e))}info(...e){this.level<=o.INFO&&console.info(...this.formatMessage("INFO",...e))}warn(...e){this.level<=o.WARN&&console.warn(...this.formatMessage("WARN",...e))}error(...e){this.level<=o.ERROR&&console.error(...this.formatMessage("ERROR",...e))}setLevel(e){this.level=e}getLevel(){return this.level}setPrefix(e){this.prefix=e}setTimestamp(e){this.enableTimestamp=e}}let l=null;function h(){return l||(l=function(e={}){return new a(e)}()),l}const c=(...e)=>h().verbose(...e),d=(...e)=>h().info(...e),u=(...e)=>h().warn(...e),g=(...e)=>h().error(...e);function p(e){const{attribute:t,hit:n,preTag:s="<mark>",postTag:i="</mark>",fallback:r}=e,o=n._highlightResult?.[t]?.value||n.highlight_result?.[t]?.value||n._highlight?.[t]||n.highlight?.[t];if(o)return o.replace(/<em>/g,s).replace(/<\/em>/g,i).replace(/<mark>/g,s).replace(/<\/mark>/g,i);const a=(l=n,t.split(".").reduce((e,t)=>e&&void 0!==e[t]?e[t]:void 0,l));var l;return void 0!==a?String(a):r||""}h();class m{constructor(e){this.listeners=[],this.debounceTimer=null,this.notifyScheduled=!1,this.searchCoalesceTimer=null,this.searchCoalesceResolvers=[],this.client=e.client,this.autoSearch=!1!==e.autoSearch,this.debounceMs=e.debounceMs||300,this.defaultSearchOptions=e.defaultSearchOptions||{widget_mode:!0},this.keepResultsOnClear=!1!==e.keepResultsOnClear,this.abTestId=e.abTestId,this.abVariant=e.abVariant,this.state={query:e.initialQuery||"",refinements:[],currentPage:1,itemsPerPage:e.itemsPerPage||10,sortBy:void 0,results:null,loading:!1,error:null},d("SearchStateManager: Initialized",{autoSearch:this.autoSearch,debounceMs:this.debounceMs})}getState(){return{...this.state}}getQuery(){return this.state.query}getRefinements(){return[...this.state.refinements]}getCurrentPage(){return this.state.currentPage}getResults(){return this.state.results}getLoading(){return this.state.loading}getError(){return this.state.error}setQuery(e,t=!0){return this.state.query===e?(c("SearchStateManager: Query unchanged, skipping update",{query:e}),void(t&&this.autoSearch&&(c("SearchStateManager: Query unchanged but triggerSearch=true, triggering search"),this.debouncedSearch()))):""===e&&this.keepResultsOnClear?(c("SearchStateManager: Query cleared, keeping previous results"),this.state.query="",this.state.currentPage=1,void this.notifyListeners()):(this.state.query=e,this.state.currentPage=1,c("SearchStateManager: Query updated",{query:e,triggerSearch:t,autoSearch:this.autoSearch}),this.notifyListeners(),void(this.autoSearch&&t?(c("SearchStateManager: Triggering debounced search"),this.debouncedSearch()):c("SearchStateManager: Search not triggered",{autoSearch:this.autoSearch,triggerSearch:t})))}addRefinement(e,t,n=!0){this.state.refinements.some(n=>n.field===e&&n.value===t)||(this.state.refinements.push({field:e,value:t}),this.state.currentPage=1,c("SearchStateManager: Refinement added",{field:e,value:t}),this.notifyListeners(),this.autoSearch&&n&&this.debouncedSearch())}removeRefinement(e,t,n=!0){const s=this.state.refinements.findIndex(n=>n.field===e&&n.value===t);-1!==s&&(this.state.refinements.splice(s,1),this.state.currentPage=1,c("SearchStateManager: Refinement removed",{field:e,value:t}),this.notifyListeners(),this.autoSearch&&n&&this.debouncedSearch())}clearRefinements(e=!0){0!==this.state.refinements.length&&(this.state.refinements=[],this.state.currentPage=1,c("SearchStateManager: Refinements cleared"),this.notifyListeners(),this.autoSearch&&e&&this.debouncedSearch())}setPage(e,t=!0){this.state.currentPage!==e&&(this.state.currentPage=e,c("SearchStateManager: Page updated",{page:e}),this.notifyListeners(),this.autoSearch&&t&&this.debouncedSearch())}setSortBy(e,t=!0){this.state.sortBy!==e&&(this.state.sortBy=e,this.state.currentPage=1,c("SearchStateManager: Sort updated",{sortBy:e}),this.notifyListeners(),this.autoSearch&&t&&this.debouncedSearch())}setItemsPerPage(e,t=!0){this.state.itemsPerPage!==e&&(this.state.itemsPerPage=e,this.state.currentPage=1,c("SearchStateManager: Items per page updated",{itemsPerPage:e}),this.notifyListeners(),this.autoSearch&&t&&this.debouncedSearch())}async search(e){return this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),new Promise((t,n)=>{this.searchCoalesceResolvers.push({resolve:t,reject:n}),this.searchCoalesceTimer&&clearTimeout(this.searchCoalesceTimer),this.searchCoalesceTimer=setTimeout(()=>{this.searchCoalesceTimer=null;const t=[...this.searchCoalesceResolvers];this.searchCoalesceResolvers=[],this._executeSearch(e).then(e=>t.forEach(t=>t.resolve(e)),e=>t.forEach(t=>t.reject(e)))},10)})}async _executeSearch(e){this.setState({loading:!0,error:null});try{const t=this.buildSearchOptions(e);c("SearchStateManager: Performing search",{query:this.state.query,refinementsCount:this.state.refinements.length,currentPage:this.state.currentPage,sortBy:this.state.sortBy,filter_by:t.filter_by});const n=await this.client.search(this.state.query,t);return this.setState({results:n,loading:!1,error:null}),d("SearchStateManager: Search completed",{query:this.state.query,resultsCount:n?.results?.length||0,totalResults:n?.totalResults||0}),n}catch(e){const t=e instanceof Error?e:new Error(String(e));return this.setState({results:null,loading:!1,error:t}),g("SearchStateManager: Search failed",{query:this.state.query,error:t.message}),null}}buildSearchOptions(e){const t={...this.defaultSearchOptions,page:this.state.currentPage,per_page:this.state.itemsPerPage,...e};if(this.state.sortBy&&"relevance"!==this.state.sortBy&&(t.sort_by=this.state.sortBy),this.state.refinements.length>0){const e={};this.state.refinements.forEach(t=>{e[t.field]||(e[t.field]=[]),e[t.field].push(t.value)});const n=[];Object.entries(e).forEach(([e,t])=>{t.forEach(t=>{n.push(`${e}:${t}`)})}),n.length>0&&(t.filter_by=n.join(" && "))}return t}debouncedSearch(){this.debounceTimer&&clearTimeout(this.debounceTimer),c("SearchStateManager: Scheduling debounced search",{debounceMs:this.debounceMs}),this.debounceTimer=setTimeout(()=>{c("SearchStateManager: Debounce timer fired, calling search()"),this.search()},this.debounceMs)}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){this.notifyScheduled||(this.notifyScheduled=!0,queueMicrotask(()=>{this.notifyScheduled=!1;const e=this.getState();this.listeners.forEach(t=>{try{t(e)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("SearchStateManager: Error in listener",{error:t.message})}})}))}clearResults(){this.setState({results:null,loading:!1,error:null}),c("SearchStateManager: Results explicitly cleared")}getAbTestId(){return this.abTestId}getAbVariant(){return this.abVariant}setAbTest(e,t){this.abTestId=e,this.abVariant=t,c("SearchStateManager: A/B test updated",{abTestId:e,abVariant:t})}buildFilterString(){if(0===this.state.refinements.length)return"";const e={};this.state.refinements.forEach(t=>{e[t.field]||(e[t.field]=[]),e[t.field].push(t.value)});const t=[];return Object.entries(e).forEach(([e,n])=>{n.forEach(n=>{t.push(`${e}:${n}`)})}),t.join(" && ")}async fetchFilters(e){c("SearchStateManager: Fetching filters",{options:e});try{const t=await this.client.getFilters({q:this.state.query||void 0,...e});return d("SearchStateManager: Filters fetched",{filterCount:t?.filters?.length}),t}catch(e){const t=e instanceof Error?e:new Error(String(e));throw g("SearchStateManager: Failed to fetch filters",{error:t.message}),t}}async searchFacetValues(e,t){c("SearchStateManager: Searching facet values",{facetName:e,query:t});try{const n=this.buildFilterString(),s=await this.client.searchFacetValues(e,{q:this.state.query||void 0,filter:n||void 0,facetQuery:t});return d("SearchStateManager: Facet values fetched",{facetName:e,valueCount:s?.values?.length}),s}catch(t){const n=t instanceof Error?t:new Error(String(t));throw g("SearchStateManager: Failed to search facet values",{facetName:e,error:n.message}),n}}async getFiltersSchema(){c("SearchStateManager: Getting filters schema");try{const e=await this.client.getFiltersSchema();return d("SearchStateManager: Filters schema fetched",{fieldCount:e?.fields?.length}),e}catch(e){const t=e instanceof Error?e:new Error(String(e));throw g("SearchStateManager: Failed to get filters schema",{error:t.message}),t}}clear(){this.state={query:"",refinements:[],currentPage:1,itemsPerPage:this.state.itemsPerPage,sortBy:void 0,results:null,loading:!1,error:null},this.notifyListeners()}}const f={colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textSecondary:"#6c757d",border:"#dee2e6",hover:"#f8f9fa",focus:"#007bff",error:"#dc3545",success:"#28a745",warning:"#ffc107"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},borderRadius:{none:"0",small:"0.25rem",medium:"0.375rem",large:"0.5rem",full:"9999px"},shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24)",medium:"0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23)",large:"0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23)"},transitions:{fast:"150ms ease-in-out",normal:"250ms ease-in-out",slow:"350ms ease-in-out"},breakpoints:{sm:"640px",md:"768px",lg:"1024px",xl:"1280px"},zIndex:{dropdown:1e3,modal:2e3,tooltip:3e3}},y=e=>((e,t)=>({colors:{...t.colors,...e.colors},typography:{...t.typography,...e.typography,fontSize:{...t.typography.fontSize,...e.typography?.fontSize}},spacing:{...t.spacing,...e.spacing},borderRadius:e.borderRadius??t.borderRadius,shadows:{...t.shadows,...e.shadows},transitions:{...t.transitions,...e.transitions},breakpoints:{...t.breakpoints,...e.breakpoints},zIndex:{...t.zIndex,...e.zIndex}}))(e,f);class S{constructor(e){c("SearchProvider: Initializing",{hasTheme:!!e.theme,enableAnalytics:!1!==e.enableAnalytics,autoTrackSearch:!1!==e.autoTrackSearch}),this.client=e.client,this.theme=e.theme?y(e.theme):f,this.enableAnalytics=!1!==e.enableAnalytics,this.autoTrackSearch=!1!==e.autoTrackSearch,this.stateManager=new m({client:this.client,autoSearch:!0,debounceMs:300,itemsPerPage:10,defaultSearchOptions:{widget_mode:!0},...e.stateManager}),S.instance=this,d("SearchProvider: Initialized successfully",{hasStateManager:!0,autoSearch:this.stateManager.getState()})}static getInstance(){return S.instance}static setInstance(e){S.instance=e}}S.instance=null;e.ClearRefinements=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("ClearRefinements: container element not found");throw g("ClearRefinements: Initialization failed",{error:e.message}),e}this.container=n,this.options={clearsQuery:t.clearsQuery??!1,resetLabel:t.resetLabel??"Clear all filters",disabledLabel:t.disabledLabel??"No filters applied",includedFields:t.includedFields,excludedFields:t.excludedFields??[],onClear:t.onClear,hideWhenEmpty:t.hideWhenEmpty??!1},this.unsubscribeStateManager=this.provider.stateManager.subscribe(()=>{this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.container.innerHTML=""}getRelevantRefinements(){return this.provider.stateManager.getRefinements().filter(e=>!this.options.excludedFields.includes(e.field)&&!(this.options.includedFields&&!this.options.includedFields.includes(e.field)))}canClear(){const e=this.getRelevantRefinements(),t=this.provider.stateManager.getQuery();return e.length>0||this.options.clearsQuery&&t.length>0}handleClick(){if(!this.canClear())return;const e=this.getRelevantRefinements();if(c("ClearRefinements: Clearing refinements",{count:e.length,clearsQuery:this.options.clearsQuery}),this.options.includedFields||this.options.excludedFields.length>0?e.forEach(e=>{this.provider.stateManager.removeRefinement(e.field,e.value,!1)}):this.provider.stateManager.clearRefinements(!1),this.options.clearsQuery?this.provider.stateManager.setQuery("",!0):e.length>0&&this.provider.stateManager.search(),this.options.onClear)try{this.options.onClear()}catch(e){const t=e instanceof Error?e:new Error(String(e));g("ClearRefinements: Error in onClear callback",{error:t.message})}}render(){this.container.innerHTML="";const e=this.canClear();if(this.options.hideWhenEmpty&&!e)return;const t=document.createElement("button");t.type="button",t.textContent=e?this.options.resetLabel:this.options.disabledLabel,t.disabled=!e,t.style.cssText=this.getButtonStyle(e),t.setAttribute("aria-label",e?this.options.resetLabel:this.options.disabledLabel),t.addEventListener("click",()=>this.handleClick()),this.container.appendChild(t)}get theme(){return this.provider.theme}getButtonStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n background-color: ${e?this.theme.colors.primary:this.theme.colors.hover};\n color: ${e?"#ffffff":this.theme.colors.textSecondary};\n border: none;\n border-radius: ${t};\n cursor: ${e?"pointer":"not-allowed"};\n opacity: ${e?"1":"0.6"};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.CurrentRefinements=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("CurrentRefinements: container element not found");throw g("CurrentRefinements: Initialization failed",{error:e.message}),e}this.container=n,this.options={showClearAll:!1!==t.showClearAll,refinements:t.refinements||[],onRefinementClear:t.onRefinementClear,onClearAll:t.onClearAll},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{this.options.refinements=e.refinements.map(e=>({field:e.field,value:e.value,label:e.field})),this.render()}),this.render()}update(e){void 0!==e.refinements&&(this.options.refinements=e.refinements,this.render())}render(){if(this.container.innerHTML="",!this.options.refinements||0===this.options.refinements.length)return;const e=document.createElement("div");if(e.style.cssText=this.getContainerStyle(),this.options.refinements.forEach((t,n)=>{const s=document.createElement("div");s.style.cssText=this.getItemStyle();const i=document.createElement("span");i.textContent=`${t.label||t.field}: `,i.style.cssText=this.getLabelStyle(),s.appendChild(i);const r=document.createElement("span");r.textContent=t.displayValue||t.value,r.style.cssText=this.getValueStyle(),s.appendChild(r);const o=document.createElement("button");o.innerHTML="×",o.type="button",o.style.cssText=this.getClearButtonStyle(),o.setAttribute("aria-label",`Clear ${t.field} filter`);o.addEventListener("click",e=>{if(e.preventDefault(),e.stopPropagation(),this.provider.stateManager.removeRefinement(t.field,t.value),this.options.onRefinementClear){c("CurrentRefinements: Refinement cleared",{field:t.field,value:t.value});try{this.options.onRefinementClear(t.field,t.value)}catch(e){const n=e instanceof Error?e:new Error(String(e));g("CurrentRefinements: Error in onRefinementClear callback",{field:t.field,value:t.value,error:n.message})}}},{passive:!1}),s.appendChild(o),e.appendChild(s)}),this.options.showClearAll&&this.options.refinements.length>1){const t=document.createElement("button");t.textContent="Clear all",t.style.cssText=this.getClearAllButtonStyle();const n=e=>{e.preventDefault(),e.stopPropagation(),this.provider.stateManager.clearRefinements(),this.options.onClearAll&&this.options.onClearAll()};t.addEventListener("click",n,{passive:!1}),e.appendChild(t)}this.container.appendChild(e)}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: ${this.theme.spacing.small};\n `}getItemStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n display: inline-flex;\n align-items: center;\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n background-color: ${this.theme.colors.hover};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n font-size: ${this.theme.typography.fontSize.small};\n `}getLabelStyle(){return`\n margin-right: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n `}getValueStyle(){return`\n margin-right: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getClearButtonStyle(){return`\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.full||"50%"};\n background-color: transparent;\n border: none;\n color: ${this.theme.colors.text};\n cursor: pointer;\n font-size: ${this.theme.typography.fontSize.medium};\n line-height: 1;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getClearAllButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.primary};\n background: transparent;\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n cursor: pointer;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.Facets=class{constructor(e,t){this.expandedFacets={},this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("Facets: container element not found");this.container=n,this.options={maxItems:t.maxItems||10,showMore:!1!==t.showMore,results:t.results,facets:t.facets,onFacetChange:t.onFacetChange},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.results&&(this.options.results=e.results),this.render()}),this.render()}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.facets&&(this.options.facets=e.facets),this.render()}render(){this.container.innerHTML="";const e=this.getFacets();0!==e.length?(c("Facets: Rendering",e.length,"facets",e),e.forEach((e,t)=>{const n=document.createElement("div");n.style.cssText=this.getFacetStyle();const s=document.createElement("div");s.style.cssText=this.getFacetHeaderStyle(),s.textContent=e.label||e.field,n.appendChild(s);const i=document.createElement("div");i.style.cssText=this.getFacetListStyle();const r=this.expandedFacets[e.field]||!1;if((r?e.items:e.items.slice(0,this.options.maxItems)).forEach((t,n)=>{const s=document.createElement("div");s.style.cssText=this.getFacetItemStyle(t.selected||!1);const r=this.provider.stateManager.getRefinements().some(n=>n.field===e.field&&n.value===t.value)||t.selected||!1,o=document.createElement("input");o.type="checkbox",o.checked=r,o.addEventListener("change",()=>{const n=o.checked;n?this.provider.stateManager.addRefinement(e.field,t.value):this.provider.stateManager.removeRefinement(e.field,t.value),this.options.onFacetChange&&this.options.onFacetChange(e.field,t.value,n)}),s.appendChild(o);const a=document.createElement("label");a.textContent=t.value,a.style.cssText=this.getFacetItemLabelStyle(),a.setAttribute("for",`facet-${e.field}-${n}`),o.id=`facet-${e.field}-${n}`;a.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o.checked=!o.checked,o.dispatchEvent(new Event("change",{bubbles:!0}))},{passive:!1}),s.appendChild(a);const l=document.createElement("span");l.textContent=`(${t.count})`,l.style.cssText=this.getFacetItemCountStyle(),s.appendChild(l),i.appendChild(s)}),this.options.showMore&&e.items.length>this.options.maxItems){const t=document.createElement("button");t.textContent=r?"Show less":`Show more (${e.items.length-this.options.maxItems})`,t.style.cssText=this.getShowMoreStyle();const n=t=>{t.preventDefault(),t.stopPropagation(),this.expandedFacets[e.field]=!r,this.render()};t.addEventListener("click",n,{passive:!1}),i.appendChild(t)}n.appendChild(i),this.container.appendChild(n)})):c("Facets: No facets found in results",{hasResults:!!this.options.results,hasFacetsOption:!!this.options.facets,resultsKeys:this.options.results?Object.keys(this.options.results):[]})}getFacets(){if(this.options.facets&&Array.isArray(this.options.facets))return this.options.facets;const e=this.options.results;if(!e)return[];let t=null;if(e&&"object"==typeof e&&("data"in e&&e.data&&"object"==typeof e.data&&"facets"in e.data&&Array.isArray(e.data.facets)&&(t=e.data.facets),!t&&"facets"in e&&Array.isArray(e.facets)&&(t=e.facets)),!t||!Array.isArray(t))return[];const n=[];for(const e of t){const t=e.field_name||e.field||e.name;if(!t)continue;const s=e.label||t,i=[];if(Array.isArray(e.counts))for(const t of e.counts){const e=t.value,n=t.count;null!=e&&null!=n&&i.push({value:String(e),count:Number(n),selected:Boolean(t.selected)})}i.length>0&&n.push({field:t,label:s,items:i})}return n}get theme(){return this.provider.theme}getFacetStyle(){return`\n margin-bottom: ${this.theme.spacing.medium};\n `}getFacetHeaderStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.bold||700};\n margin-bottom: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getFacetListStyle(){return`\n display: flex;\n flex-direction: column;\n gap: ${this.theme.spacing.small};\n `}getFacetItemStyle(e){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n padding: ${this.theme.spacing.small};\n cursor: pointer;\n background-color: ${e?this.theme.colors.hover:"transparent"};\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getFacetItemLabelStyle(){return`\n flex: 1;\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n cursor: pointer;\n `}getFacetItemCountStyle(){return`\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n opacity: 0.7;\n `}getShowMoreStyle(){return"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small,`\n padding: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.primary};\n background: none;\n border: none;\n cursor: pointer;\n text-align: left;\n margin-top: ${this.theme.spacing.small};\n `}},e.HitsPerPage=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("HitsPerPage: container element not found");throw g("HitsPerPage: Initialization failed",{error:e.message}),e}this.container=n;const s=t.items.find(e=>e.default)||t.items[0];this.currentValue=s?.value||10,this.options={items:t.items,label:t.label??"Show",onHitsPerPageChange:t.onHitsPerPageChange},this.provider.stateManager.setItemsPerPage(this.currentValue,!1),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.itemsPerPage!==this.currentValue&&(this.currentValue=e.itemsPerPage,this.render())}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.container.innerHTML=""}update(e){e.items&&(this.options.items=e.items,this.render())}render(){this.container.innerHTML="";const e=document.createElement("div");if(e.style.cssText=this.getContainerStyle(),this.options.label){const t=document.createElement("label");t.textContent=this.options.label,t.style.cssText=this.getLabelStyle(),e.appendChild(t)}const t=document.createElement("select");t.value=this.currentValue.toString(),t.style.cssText=this.getSelectStyle(),t.setAttribute("aria-label","Results per page"),t.addEventListener("change",e=>{const t=e.target,n=parseInt(t.value,10);if(this.currentValue=n,c("HitsPerPage: Value changed",{value:n}),this.provider.stateManager.setItemsPerPage(n,!1),this.provider.stateManager.setPage(1,!0),this.options.onHitsPerPageChange)try{this.options.onHitsPerPageChange(n)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("HitsPerPage: Error in onHitsPerPageChange callback",{value:n,error:t.message})}}),this.options.items.forEach(e=>{const n=document.createElement("option");n.value=e.value.toString(),n.textContent=e.label,e.value===this.currentValue&&(n.selected=!0),t.appendChild(n)}),e.appendChild(t),this.container.appendChild(e)}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n `}getLabelStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n `}getSelectStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n cursor: pointer;\n outline: none;\n `}},e.InfiniteHits=class{constructor(e,t){this.accumulatedHits=[],this.isLoadingMore=!1,this.currentPage=1,this.observer=null,this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("InfiniteHits: container element not found");throw g("InfiniteHits: Initialization failed",{error:e.message}),e}this.container=n,this.options={renderHit:t.renderHit,renderEmpty:t.renderEmpty,showMoreButton:!1!==t.showMoreButton,useInfiniteScroll:t.useInfiniteScroll??!1,scrollThreshold:t.scrollThreshold??.1,fieldMapping:t.fieldMapping,showMoreLabel:t.showMoreLabel??"Show more",onHitClick:t.onHitClick},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{const t=e.currentPage,n=this.extractHits(e.results);1===t?(this.accumulatedHits=n,this.currentPage=1):t>this.currentPage&&(this.accumulatedHits=[...this.accumulatedHits,...n],this.currentPage=t),this.isLoadingMore=!1,this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.observer&&(this.observer.disconnect(),this.observer=null),this.container.innerHTML=""}extractHits(e){return e?e.results?e.results:e.hits?e.hits:Array.isArray(e)?e:[]:[]}get isLastPage(){const e=this.provider.stateManager.getState(),t=e.results?.totalResults||e.results?.found||0,n=e.itemsPerPage||10,s=Math.ceil(t/n);return e.currentPage>=s}handleShowMore(){if(this.isLastPage||this.isLoadingMore)return;this.isLoadingMore=!0;const e=this.provider.stateManager.getCurrentPage()+1;c("InfiniteHits: Loading more",{nextPage:e}),this.provider.stateManager.setPage(e),this.render()}render(){this.container.innerHTML="";const e=this.provider.stateManager.getState();if(e.loading&&0===this.accumulatedHits.length)return;if(!e.loading&&0===this.accumulatedHits.length){const e=this.options.renderEmpty?this.options.renderEmpty():this.createDefaultEmpty();return void this.container.appendChild(e)}const t=document.createElement("div");if(this.accumulatedHits.forEach((e,n)=>{const s=this.options.renderHit?this.options.renderHit(e,n):this.createDefaultHit(e,n);t.appendChild(s)}),this.container.appendChild(t),this.options.showMoreButton&&!this.options.useInfiniteScroll&&!this.isLastPage){const e=this.createShowMoreButton();this.container.appendChild(e)}if(this.options.useInfiniteScroll&&!this.isLastPage){const e=document.createElement("div");e.style.cssText="height: 1px; visibility: hidden;",this.container.appendChild(e),this.setupIntersectionObserver(e)}}setupIntersectionObserver(e){this.observer&&this.observer.disconnect(),this.observer=new IntersectionObserver(e=>{!e[0].isIntersecting||this.isLastPage||this.isLoadingMore||this.handleShowMore()},{threshold:this.options.scrollThreshold}),this.observer.observe(e)}createDefaultHit(e,t){const n=document.createElement("div");n.style.cssText=this.getHitStyle();if(this.options.fieldMapping){const t=this.extractField(e,"image");if(t){const s=document.createElement("img");s.src=t,s.alt=this.extractField(e,"title")||"",s.style.cssText=this.getImageStyle(),n.appendChild(s)}const s=document.createElement("div");s.style.cssText="flex: 1;";const i=this.extractField(e,"title");if(i){const e=document.createElement("h3");e.textContent=i,e.style.cssText=this.getTitleStyle(),s.appendChild(e)}const r=this.extractField(e,"description");if(r){const e=document.createElement("p");e.textContent=r,e.style.cssText=this.getDescriptionStyle(),s.appendChild(e)}const o=this.extractFieldValue(e,"price");if(null!=o&&""!==o){const e=document.createElement("span"),t="number"==typeof o?o.toFixed(2):String(o);e.textContent=`$${t}`,e.style.cssText=this.getPriceStyle(),s.appendChild(e)}n.appendChild(s)}else{const t=document.createElement("div");t.style.cssText="flex: 1;";Object.keys(e).slice(0,5).forEach(n=>{const s=e[n];if(null!=s&&"object"!=typeof s){const e=document.createElement("div");e.innerHTML=`<strong>${n}:</strong> ${String(s)}`,e.style.cssText=`margin-bottom: ${this.theme.spacing.small}; font-size: ${this.theme.typography.fontSize.small};`,t.appendChild(e)}}),n.appendChild(t)}return this.options.onHitClick&&(n.style.cursor="pointer",n.addEventListener("click",()=>this.options.onHitClick(e,t))),n}createDefaultEmpty(){const e=document.createElement("div");return e.textContent="No results found",e.style.cssText=`\n padding: ${this.theme.spacing.large};\n text-align: center;\n color: ${this.theme.colors.textSecondary};\n `,e}createShowMoreButton(){const e=document.createElement("button");return e.type="button",e.textContent=this.options.showMoreLabel,e.disabled=this.isLoadingMore,e.style.cssText=this.getShowMoreButtonStyle(),e.addEventListener("click",()=>this.handleShowMore()),e}extractField(e,t){if(!this.options.fieldMapping||!this.options.fieldMapping[t]){const n=e[t];return null!=n?String(n):""}const n=this.options.fieldMapping[t];if("string"!=typeof n){const n=e[t];return null!=n?String(n):""}const s=e[n];return null!=s?String(s):""}extractFieldValue(e,t){if(!this.options.fieldMapping||!this.options.fieldMapping[t]){const n=e[t];return null!=n?n:void 0}const n=this.options.fieldMapping[t];if("string"!=typeof n){const n=e[t];return null!=n?n:void 0}const s=e[n];return null!=s?s:void 0}get theme(){return this.provider.theme}getHitStyle(){return"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small,`\n display: flex;\n gap: ${this.theme.spacing.medium};\n padding: ${this.theme.spacing.medium};\n border-bottom: 1px solid ${this.theme.colors.border};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getImageStyle(){return`\n width: 80px;\n height: 80px;\n object-fit: cover;\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.small};\n `}getTitleStyle(){return`\n margin: 0;\n margin-bottom: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.semibold||600};\n color: ${this.theme.colors.text};\n `}getDescriptionStyle(){return`\n margin: 0;\n font-size: ${this.theme.typography.fontSize.small};\n color: ${this.theme.colors.textSecondary};\n line-height: ${this.theme.typography.lineHeight?.normal||1.5};\n `}getPriceStyle(){return`\n display: inline-block;\n margin-top: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.bold||700};\n color: ${this.theme.colors.primary};\n `}getShowMoreButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n display: block;\n width: 100%;\n padding: ${this.theme.spacing.medium};\n margin-top: ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n background-color: ${this.isLoadingMore?this.theme.colors.hover:this.theme.colors.primary};\n color: ${this.isLoadingMore?this.theme.colors.textSecondary:"#ffffff"};\n border: none;\n border-radius: ${e};\n cursor: ${this.isLoadingMore?"not-allowed":"pointer"};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.Pagination=class{constructor(e,t){this.unsubscribeStateManager=null,console.log("Pagination: Constructor called",{options:t}),this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("Pagination: container element not found");throw g("Pagination: Initialization failed",{error:e.message}),e}console.log("Pagination: Container found",{container:n,containerId:n.id,containerTag:n.tagName}),this.container=n,this.currentPage=t.currentPage||1,this.options={itemsPerPage:t.itemsPerPage||10,showFirstLast:!1!==t.showFirstLast,showPrevNext:!1!==t.showPrevNext,results:t.results,currentPage:t.currentPage||1,onPageChange:t.onPageChange};this.container.addEventListener("click",e=>{const t=e.target;if(console.log("Pagination: Container clicked",{target:t.tagName,targetClass:t.className,hasDataPage:t.hasAttribute("data-page"),closestButton:t.closest("button[data-page]")}),"SPAN"===t.tagName||"DIV"===t.tagName){if(!t.closest("button[data-page]"))return}const n="BUTTON"===t.tagName&&t.hasAttribute("data-page")?t:t.closest("button[data-page]");if(n){e.preventDefault(),e.stopPropagation();const t=n.getAttribute("data-page"),s=t?parseInt(t,10):0;if(console.log("Pagination: Button found",{page:s,currentPage:this.currentPage,pageStr:t,button:n,isValid:s>0&&s!==this.currentPage}),s>0)if(console.log("Pagination: Processing page change",{page:s,currentPage:this.currentPage,willUpdate:s!==this.currentPage}),s!==this.currentPage){if(this.provider.stateManager.setPage(s),this.options.onPageChange)try{this.options.onPageChange(s)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("Pagination: Error in onPageChange callback",{page:s,error:t.message})}}else console.log("Pagination: Page is already current, skipping update",{page:s});else console.warn("Pagination: Invalid page number",{page:s,pageStr:t,button:n})}else console.log("Pagination: Click not on a button",{target:t.tagName})},{passive:!1}),console.log("Pagination: Event delegation listener attached to container",{container:this.container}),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.results&&(this.options.results=e.results),e.currentPage!==this.currentPage&&(this.currentPage=e.currentPage),this.render()}),this.render()}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.currentPage&&(this.currentPage=e.currentPage),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}render(){console.log("🔵 Pagination.render() START",{container:this.container,containerId:this.container.id,currentPage:this.currentPage,hasResults:!!this.options.results}),this.container.innerHTML="";const e=this.getTotalPages();if(console.log("🔵 Pagination: Total pages calculated",{totalPages:e}),e<=1)return console.log("🔵 Pagination: NOT RENDERING - totalPages <= 1",{totalPages:e}),void c("Pagination: Not rendering, totalPages <= 1",{totalPages:e});console.log("🔵 Pagination: WILL RENDER",{currentPage:this.currentPage,totalPages:e,hasResults:!!this.options.results}),c("Pagination: Rendering",{currentPage:this.currentPage,totalPages:e,hasResults:!!this.options.results});const t=document.createElement("div");if(t.style.cssText=this.getContainerStyle(),t.setAttribute("data-pagination-wrapper","true"),console.log("Pagination: Created paginationDiv",{paginationDiv:t,style:t.style.cssText,container:this.container}),this.options.showFirstLast&&this.currentPage>1){const e=this.createButton("First",1);t.appendChild(e)}if(this.options.showPrevNext&&this.currentPage>1){const e=this.createButton("Previous",this.currentPage-1);t.appendChild(e)}let n,s;if(e<=5)n=1,s=e;else{const t=Math.floor(2.5);this.currentPage<=t+1?(n=1,s=5):this.currentPage>=e-t?(n=e-5+1,s=e):(n=this.currentPage-t,s=this.currentPage+t)}if(n>1){const e=document.createElement("span");e.textContent="...",e.style.cssText=`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n `,t.appendChild(e)}console.log("🔵 Pagination: Rendering page buttons",{startPage:n,endPage:s,currentPage:this.currentPage});for(let e=n;e<=s;e++){console.log("🔵 Pagination: Creating page button",{i:e,isActive:e===this.currentPage});const n=this.createButton(String(e),e,e===this.currentPage);t.appendChild(n),console.log("🔵 Pagination: Page button appended",{page:e,button:n})}if(s<e){const e=document.createElement("span");e.textContent="...",e.style.cssText=`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n `,t.appendChild(e)}if(this.options.showPrevNext&&this.currentPage<e){const e=this.createButton("Next",this.currentPage+1);t.appendChild(e)}if(this.options.showFirstLast&&this.currentPage<e){const n=this.createButton("Last",e);t.appendChild(n)}console.log("🔵 Pagination: About to append paginationDiv to container",{paginationDiv:t,container:this.container,containerChildrenBefore:this.container.children.length,paginationDivChildren:t.children.length}),this.container.appendChild(t),console.log("🔵 Pagination: paginationDiv appended to container",{containerChildrenAfter:this.container.children.length,containerHTML:this.container.innerHTML.substring(0,300)});const i=this.container.querySelectorAll("button[data-page]");console.log("🔵 Pagination: Render complete - buttons in DOM",{buttonCount:i.length,buttons:Array.from(i).map(e=>{const t=e;return{text:t.textContent,page:t.getAttribute("data-page"),element:t,parent:t.parentElement?.tagName}})}),console.log("🔵 Pagination: Testing direct click handler");const r=this.container.querySelector("button[data-page]");r?(console.log("🔵 Pagination: Found test button, adding DIRECT listener",{testButton:r,page:r.getAttribute("data-page"),text:r.textContent}),r.addEventListener("click",e=>{console.log("🟢🟢🟢 DIRECT BUTTON CLICK HANDLER FIRED! 🟢🟢🟢",{e:e,button:r,page:r.getAttribute("data-page"),target:e.target}),e.preventDefault(),e.stopPropagation()},{passive:!1,capture:!0}),console.log("🔵 Pagination: Direct listener attached to test button")):console.warn("🔴 Pagination: NO TEST BUTTON FOUND for direct listener!"),console.log("🔵 Pagination.render() END")}getTotalPages(){if(!this.options.results)return 0;let e;if("number"==typeof this.options.results.totalResults)e=this.options.results.totalResults;else if("number"==typeof this.options.results.total)e=this.options.results.total;else{const t=this.options.results.results?.length||0;u("Pagination: Using results array length as total (totalResults not found)",{resultsLength:t,responseKeys:Object.keys(this.options.results)}),e=t}const t=Math.ceil(e/this.options.itemsPerPage);return c("Pagination: Calculating total pages",{total:e,itemsPerPage:this.options.itemsPerPage,totalPages:t,currentPage:this.currentPage}),t}createButton(e,t,n=!1){const s=document.createElement("button");return s.textContent=e,s.style.cssText=this.getButtonStyle(n),s.type="button",s.setAttribute("data-page",String(t)),s}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n flex-wrap: wrap;\n `}getButtonStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium,n=this.theme.transitions?.fast||"150ms ease-in-out";return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${t};\n background-color: ${e?this.theme.colors.primary:this.theme.colors.background};\n color: ${e?"#ffffff":this.theme.colors.text};\n cursor: pointer;\n transition: ${n};\n `}},e.QuerySuggestions=class{constructor(e,t){this.suggestions=[],this.loading=!1,this.error=null,this.selectedIndex=-1,this.debounceTimer=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("QuerySuggestions: container element not found");this.container=n,this.options={query:t.query||"",maxSuggestions:t.maxSuggestions||10,debounceMs:t.debounceMs||300,minQueryLength:t.minQueryLength||2,showTitle:t.showTitle||!1,title:t.title||"Suggestions",onSuggestionClick:t.onSuggestionClick};const s=this.options.query??"";s.length>=this.options.minQueryLength&&this.loadSuggestions(s)}update(e){void 0!==e.query&&(this.options.query=e.query,this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.options.query&&this.options.query.length>=this.options.minQueryLength?this.loadSuggestions(this.options.query):(this.suggestions=[],this.render())},this.options.debounceMs))}async loadSuggestions(e){this.loading=!0,this.error=null;try{const t=await this.provider.client.getSuggestions(e,this.options.maxSuggestions),n=Array.isArray(t)?t:[];this.suggestions=n.map(e=>{const t=e.query??e.text??e,n=void 0!==e.popularity?e.popularity:void 0!==e.count?e.count:void 0;return{query:"string"==typeof t?t:String(t),count:"number"==typeof n?n:void 0,metadata:e}}).slice(0,this.options.maxSuggestions),this.loading=!1,this.render(),c("QuerySuggestions: Suggestions loaded",{query:this.options.query,count:this.suggestions.length})}catch(e){const t=e instanceof Error?e:new Error(String(e));g("QuerySuggestions: Failed to load suggestions",{query:this.options.query,error:t.message,stack:t.stack}),this.error=t,this.loading=!1,this.render()}}render(){if(this.container.innerHTML="",!this.options.query||this.options.query.length<this.options.minQueryLength)return;if(this.error||0===this.suggestions.length){const e=document.createElement("div");return e.style.cssText=this.getEmptyStyle(),e.textContent="No suggestions available",void this.container.appendChild(e)}if(this.options.showTitle){const e=document.createElement("div");e.style.cssText=this.getTitleStyle(),e.textContent=this.options.title,this.container.appendChild(e)}const e=document.createElement("div");e.style.cssText=this.getListStyle(),this.suggestions.forEach((t,n)=>{const s=document.createElement("div");s.style.cssText=this.getSuggestionStyle(n===this.selectedIndex);s.addEventListener("click",e=>{if(e.preventDefault(),e.stopPropagation(),this.options.onSuggestionClick){c("QuerySuggestions: Suggestion clicked",{suggestion:t.query});try{this.options.onSuggestionClick(t.query)}catch(e){const n=e instanceof Error?e:new Error(String(e));g("QuerySuggestions: Error in onSuggestionClick callback",{suggestion:t.query,error:n.message})}}},{passive:!1}),s.addEventListener("mouseenter",()=>{this.selectedIndex=n,this.render()}),s.addEventListener("mouseleave",()=>{this.selectedIndex=-1,this.render()});const i=document.createElement("span");if(i.textContent=t.query,s.appendChild(i),void 0!==t.count){const e=document.createElement("span");e.textContent=` (${t.count})`,e.style.cssText=this.getCountStyle(),s.appendChild(e)}e.appendChild(s)}),this.container.appendChild(e)}get theme(){return this.provider.theme}getTitleStyle(){return`\n font-size: ${this.theme.typography.fontSize.large};\n font-weight: bold;\n margin-bottom: ${this.theme.spacing.medium};\n color: ${this.theme.colors.text};\n `}getEmptyStyle(){return`\n padding: ${this.theme.spacing.medium};\n text-align: center;\n color: ${this.theme.colors.text};\n opacity: 0.6;\n `}getListStyle(){return"\n display: flex;\n flex-direction: column;\n "}getSuggestionStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.medium};\n cursor: pointer;\n border-radius: ${t};\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n background-color: ${e?this.theme.colors.hover:"transparent"};\n margin-bottom: ${this.theme.spacing.small};\n `}getCountStyle(){return`\n opacity: 0.6;\n margin-left: ${this.theme.spacing.small};\n `}destroy(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.container.innerHTML=""}},e.RangeInput=class{constructor(e,t){this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("RangeInput: container element not found");throw g("RangeInput: Initialization failed",{error:e.message}),e}this.container=n,this.internalMin=t.currentMin,this.internalMax=t.currentMax,this.options={field:t.field,label:t.label??"",min:t.min??0,max:t.max??100,step:t.step??1,showApplyButton:!1!==t.showApplyButton,placeholder:t.placeholder??{min:"Min",max:"Max"},currentMin:t.currentMin,currentMax:t.currentMax,onRangeChange:t.onRangeChange},this.render()}update(e){void 0!==e.currentMin&&(this.internalMin=e.currentMin,this.options.currentMin=e.currentMin),void 0!==e.currentMax&&(this.internalMax=e.currentMax,this.options.currentMax=e.currentMax),this.render()}render(){if(this.container.innerHTML="",this.options.label){const e=document.createElement("label");e.textContent=this.options.label,e.style.cssText=this.getLabelStyle(),this.container.appendChild(e)}const e=document.createElement("div");e.style.cssText=this.getInputGroupStyle();const t=document.createElement("input");t.type="number",t.min=this.options.min?.toString()||"",t.max=this.options.max?.toString()||"",t.step=this.options.step.toString(),t.value=void 0!==this.internalMin?this.internalMin.toString():"",t.placeholder=this.options.placeholder?.min??"Min",t.style.cssText=this.getInputStyle(),t.addEventListener("input",e=>{const t=e.target,n=""===t.value?void 0:parseFloat(t.value);if(this.internalMin=n,!this.options.showApplyButton&&(this.updateStateManager(n,this.internalMax),this.options.onRangeChange)){c("RangeInput: Min value changed",{field:this.options.field,min:n,max:this.internalMax});try{this.options.onRangeChange(n,this.internalMax)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("RangeInput: Error in onRangeChange callback",{field:this.options.field,error:t.message})}}}),e.appendChild(t);const n=document.createElement("span");n.textContent="to",n.style.cssText=this.getSeparatorStyle(),e.appendChild(n);const s=document.createElement("input");if(s.type="number",s.min=this.options.min?.toString()||"",s.max=this.options.max?.toString()||"",s.step=this.options.step.toString(),s.value=void 0!==this.internalMax?this.internalMax.toString():"",s.placeholder=this.options.placeholder?.max??"Max",s.style.cssText=this.getInputStyle(),s.addEventListener("input",e=>{const t=e.target,n=""===t.value?void 0:parseFloat(t.value);if(this.internalMax=n,!this.options.showApplyButton&&(this.updateStateManager(this.internalMin,n),this.options.onRangeChange)){c("RangeInput: Max value changed",{field:this.options.field,min:this.internalMin,max:n});try{this.options.onRangeChange(this.internalMin,n)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("RangeInput: Error in onRangeChange callback",{field:this.options.field,error:t.message})}}}),e.appendChild(s),this.options.showApplyButton){const t=document.createElement("button");t.textContent="Apply",t.style.cssText=this.getApplyButtonStyle();const n=e=>{if(e.preventDefault(),e.stopPropagation(),this.updateStateManager(this.internalMin,this.internalMax),this.options.onRangeChange){c("RangeInput: Apply button clicked",{field:this.options.field,min:this.internalMin,max:this.internalMax});try{this.options.onRangeChange(this.internalMin,this.internalMax)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("RangeInput: Error in onRangeChange callback",{field:this.options.field,error:t.message})}}};t.addEventListener("click",n,{passive:!1}),e.appendChild(t)}if(this.hasValue()){const t=document.createElement("button");t.textContent="Reset",t.style.cssText=this.getResetButtonStyle();const n=e=>{e.preventDefault(),e.stopPropagation(),this.internalMin=void 0,this.internalMax=void 0;this.provider.stateManager.getRefinements().forEach(e=>{e.field===this.options.field&&this.provider.stateManager.removeRefinement(e.field,e.value)}),this.render(),this.options.onRangeChange&&this.options.onRangeChange(void 0,void 0)};t.addEventListener("click",n,{passive:!1}),e.appendChild(t)}this.container.appendChild(e)}hasValue(){return void 0!==this.internalMin||void 0!==this.internalMax}updateStateManager(e,t){this.provider.stateManager.getRefinements().forEach(e=>{e.field===this.options.field&&this.provider.stateManager.removeRefinement(e.field,e.value,!1)}),void 0!==e&&this.provider.stateManager.addRefinement(this.options.field,`>=${e}`,!1),void 0!==t&&this.provider.stateManager.addRefinement(this.options.field,`<=${t}`,!1),void 0===e&&void 0===t||this.provider.stateManager.search()}get theme(){return this.provider.theme}getLabelStyle(){return`\n display: block;\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n margin-bottom: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getInputGroupStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n flex-wrap: wrap;\n `}getInputStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n flex: 1;\n min-width: 80px;\n padding: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n outline: none;\n `}getSeparatorStyle(){return`\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n font-size: ${this.theme.typography.fontSize.medium};\n `}getApplyButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n background-color: ${this.theme.colors.primary};\n color: #ffffff;\n border: none;\n border-radius: ${e};\n cursor: pointer;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}getResetButtonStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n background-color: transparent;\n color: ${this.theme.colors.text};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n cursor: pointer;\n transition: ${this.theme.transitions?.fast||"150ms ease-in-out"};\n `}},e.RatingDisplay=s,e.SearchBar=class{constructor(e,t){this.suggestions=[],this.richSuggestionsData=null,this.selectedIndex=-1,this.debounceTimer=null,this.isFocused=!1,this.unsubscribeStateManager=null,e instanceof S?(this.provider=e,this.client=this.provider.client):(this.provider=new S({client:e}),this.client=e);const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("SearchBar: container element not found");this.container=n,this.options={placeholder:t.placeholder||"Powered by Seekora",showSuggestions:!1!==t.showSuggestions,minQueryLength:t.minQueryLength||1,maxSuggestions:t.maxSuggestions||10,debounceMs:t.debounceMs||300,enableRichSuggestions:!1!==t.enableRichSuggestions,onSearch:t.onSearch,onSuggestionSelect:t.onSuggestionSelect,onProductClick:t.onProductClick,onBrandClick:t.onBrandClick,searchOptions:t.searchOptions},this.render(),this.attachEventListeners(),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{if(this.input.value!==e.query&&(this.input.value=e.query),e.results){const t=e.results,n=t.processingTimeMS||t.data?.processingTimeMS||t.data?.data?.processingTimeMS;void 0!==n?(this.responseTimeElement.textContent=`${n}ms`,this.responseTimeElement.style.display="inline"):this.responseTimeElement.style.display="none"}else this.responseTimeElement.style.display="none";e.results&&this.options.onSearch&&this.options.onSearch(e.query,e.results)})}render(){this.container.style.position="relative",this.container.style.display="flex",this.container.style.alignItems="center",this.inputWrapper=document.createElement("div"),this.inputWrapper.style.cssText="position: relative; flex: 1; display: flex; align-items: center;",this.input=document.createElement("input"),this.input.type="text",this.input.placeholder=this.options.placeholder,this.input.style.cssText=this.getInputStyle(),this.injectPlaceholderStyles(),this.inputWrapper.appendChild(this.input),this.responseTimeElement=document.createElement("span"),this.responseTimeElement.style.cssText=this.getResponseTimeStyle(),this.responseTimeElement.style.display="none",this.inputWrapper.appendChild(this.responseTimeElement),this.container.appendChild(this.inputWrapper),this.suggestionsContainer=document.createElement("div"),this.suggestionsContainer.style.cssText=this.getSuggestionsContainerStyle(),this.suggestionsContainer.style.display="none",this.container.appendChild(this.suggestionsContainer)}injectPlaceholderStyles(){const e=this.provider.theme;this.input.id||(this.input.id="seekora-search-input-"+Math.random().toString(36).substr(2,9));const t=`seekora-searchbar-placeholder-${this.input.id}`,n=document.getElementById(t);n&&n.remove();const s=document.createElement("style");s.id=t;const i=e.colors.textSecondary||e.colors.text;s.textContent=`\n #${this.input.id}::placeholder {\n color: ${i};\n opacity: 0.6;\n }\n `,document.head.appendChild(s)}attachEventListeners(){this.input.addEventListener("input",e=>{const t=e.target.value;this.handleInputChange(t)}),this.input.addEventListener("focus",()=>{this.isFocused=!0,this.options.showSuggestions&&this.options.enableRichSuggestions?(console.log("🔍 SearchBar: Input focused, fetching empty query suggestions"),this.handleInputChange("")):this.updateSuggestionsVisibility()}),this.input.addEventListener("blur",e=>{const t=e.relatedTarget;t&&this.suggestionsContainer.contains(t)||setTimeout(()=>{this.suggestionsContainer.contains(document.activeElement)||(this.isFocused=!1,this.updateSuggestionsVisibility(),this.selectedIndex=-1)},100)}),this.input.addEventListener("keydown",e=>{this.handleKeyDown(e)})}handleInputChange(e){this.selectedIndex=-1,this.debounceTimer&&clearTimeout(this.debounceTimer);const t=this.options.enableRichSuggestions;e.trim().length;const n=e.length>=this.options.minQueryLength;return this.options.showSuggestions&&(t||n)?void(this.debounceTimer=setTimeout(async()=>{try{if(this.options.enableRichSuggestions)console.log("🚀 SearchBar: enableRichSuggestions is TRUE, calling fetchRichSuggestions for query:",e||"(empty)"),await this.fetchRichSuggestions(e);else{console.log("⚠️ SearchBar: enableRichSuggestions is FALSE, using basic suggestions");const t=await this.client.getSuggestions(e,this.options.maxSuggestions),n=Array.isArray(t)?t:[];this.suggestions=n.map(e=>{const t=e.query??e.text??e,n=void 0!==e.popularity?e.popularity:void 0!==e.count?e.count:void 0;return{query:"string"==typeof t?t:String(t),count:"number"==typeof n?n:void 0,metadata:e}}),this.richSuggestionsData=null}this.renderSuggestions()}catch(e){g("Error fetching suggestions:",e),this.suggestions=[],this.richSuggestionsData=null,this.renderSuggestions()}},this.options.debounceMs)):(this.suggestions=[],void this.renderSuggestions())}handleKeyDown(e){switch(e.key){case"ArrowDown":e.preventDefault(),this.suggestions.length>0&&(this.selectedIndex=this.selectedIndex<this.suggestions.length-1?this.selectedIndex+1:this.selectedIndex,this.renderSuggestions());break;case"ArrowUp":e.preventDefault(),this.suggestions.length>0&&(this.selectedIndex=this.selectedIndex>0?this.selectedIndex-1:-1,this.renderSuggestions());break;case"Enter":e.preventDefault(),this.suggestions.length>0&&this.selectedIndex>=0&&this.selectedIndex<this.suggestions.length?this.selectSuggestion(this.suggestions[this.selectedIndex].query):this.performSearch();break;case"Escape":this.isFocused=!1,this.selectedIndex=-1,this.updateSuggestionsVisibility(),this.input.blur()}}selectSuggestion(e){this.input.value=e,this.selectedIndex=-1,this.isFocused=!1,this.updateSuggestionsVisibility(),this.input.blur(),this.options.onSuggestionSelect&&this.options.onSuggestionSelect(e),this.performSearch()}async fetchRichSuggestions(e){try{c("SearchBar: Fetching rich suggestions via client.getSuggestions",{query:e});const t=await this.client.getSuggestions(e,{include_dropdown_recommendations:!0,hitsPerPage:this.options.maxSuggestions,returnFullResponse:!0}),n=t.suggestions||[],s=t.extensions,i=t.raw||{},r={status:"success",data:{hits:n,nbHits:n.length,page:i.page||0,hitsPerPage:i.hitsPerPage||this.options.maxSuggestions,processingTimeMS:i.processingTimeMS||0,query:e,indexUsed:i.indexUsed||"",parsedQuery:i.parsedQuery||e,dropdown_recommendations:s?{trending_searches:s.trending_searches,trending_products:s.trending_products,popular_brands:s.popular_brands,processing_time_ms:s.processing_time_ms||0,cached_at:s.cached_at}:void 0},timestamp:i.timestamp||(new Date).toISOString(),version:i.version||""};this.richSuggestionsData=r,this.suggestions=n.map(e=>({query:e.query,count:e.popularity,metadata:e})),c("SearchBar: Rich suggestions loaded",{query:e,suggestionsCount:this.suggestions.length,hasTrendingSearches:!!r.data.dropdown_recommendations?.trending_searches?.length,hasTrendingProducts:!!r.data.dropdown_recommendations?.trending_products?.length,hasPopularBrands:!!r.data.dropdown_recommendations?.popular_brands?.length})}catch(t){const n=t instanceof Error?t:new Error(String(t));g("SearchBar: Failed to fetch rich suggestions, falling back to basic",{error:n.message,query:e}),await this.fallbackToBasicSuggestions(e)}}async fallbackToBasicSuggestions(e){try{const t=await this.client.getSuggestions(e,this.options.maxSuggestions),n=Array.isArray(t)?t:[];this.suggestions=n.map(e=>{const t=e.query??e.text??e,n=void 0!==e.popularity?e.popularity:void 0!==e.count?e.count:void 0;return{query:"string"==typeof t?t:String(t),count:"number"==typeof n?n:void 0,metadata:e}}),this.richSuggestionsData=null}catch(e){g("SearchBar: Fallback suggestions also failed",e),this.suggestions=[],this.richSuggestionsData=null}}async performSearch(){const e=this.input.value.trim();c("SearchBar: Setting query in state manager",{query:e}),this.provider.stateManager.setQuery(e)}renderSuggestions(){this.suggestionsContainer.innerHTML="";const e=this.richSuggestionsData?.data?.dropdown_recommendations,t=e?this.richSuggestionsData.data.dropdown_recommendations:null;console.log("🎨 SearchBar: renderSuggestions called",{hasRichData:e,recommendationsKeys:t?Object.keys(t):[],trendingSearchesCount:t?.trending_searches?.length||0,trendingProductsCount:t?.trending_products?.length||0,popularBrandsCount:t?.popular_brands?.length||0,suggestionsCount:this.suggestions.length});const n=this.suggestions.slice(0,this.options.maxSuggestions);if(n.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const t=document.createElement("div");t.style.cssText=this.getSectionTitleStyle(),t.textContent="Suggestions",e.appendChild(t);const s=document.createElement("div");s.style.cssText=this.getSuggestionsListStyle(),n.forEach((e,t)=>{const n=document.createElement("div");n.style.cssText=this.getSuggestionItemStyle(t===this.selectedIndex);const i=document.createElement("span");if(i.textContent=e.query,n.appendChild(i),void 0!==e.count){const t=document.createElement("span");t.textContent=` (${e.count})`,t.style.cssText=this.getCountStyle(),n.appendChild(t)}n.addEventListener("mousedown",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),n.addEventListener("click",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),s.appendChild(n)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}if(t?.trending_searches&&t.trending_searches.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const n=document.createElement("div");n.style.cssText=this.getSectionTitleStyle(),n.textContent="Trending Searches",e.appendChild(n);const s=document.createElement("div");s.style.cssText=this.getSuggestionsListStyle(),t.trending_searches.forEach(e=>{const t=document.createElement("div");t.style.cssText=this.getSuggestionItemStyle(!1);const n=document.createElement("span");if(n.textContent=e.query,t.appendChild(n),void 0!==e.searches){const n=document.createElement("span");n.textContent=` (${e.searches})`,n.style.cssText=this.getCountStyle(),t.appendChild(n)}t.addEventListener("mousedown",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),t.addEventListener("click",t=>{t.preventDefault(),this.selectSuggestion(e.query)}),s.appendChild(t)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}if(t?.trending_products&&t.trending_products.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const n=document.createElement("div");n.style.cssText=this.getSectionTitleStyle(),n.textContent="Trending Products",e.appendChild(n);const s=document.createElement("div");s.style.cssText=this.getProductsGridStyle(),t.trending_products.forEach(e=>{const t=document.createElement("div");if(t.style.cssText=this.getProductCardStyle(),e.image){const n=document.createElement("img");n.src=e.image,n.alt=e.title,n.style.cssText=this.getProductImageStyle(),n.onerror=()=>{n.style.display="none"},t.appendChild(n)}const n=document.createElement("div");n.style.cssText=this.getProductInfoStyle();const i=document.createElement("div");if(i.style.cssText=this.getProductTitleStyle(),i.textContent=e.title,n.appendChild(i),void 0!==e.price){const t=document.createElement("div");t.style.cssText=this.getProductPriceStyle();const s=e.currency||"$";t.textContent=`${s}${e.price}`,n.appendChild(t)}t.appendChild(n),t.addEventListener("mousedown",t=>{t.preventDefault(),this.options.onProductClick?this.options.onProductClick(e.id,e):e.url&&(window.location.href=e.url)}),t.addEventListener("click",t=>{t.preventDefault(),this.options.onProductClick?this.options.onProductClick(e.id,e):e.url&&(window.location.href=e.url)}),s.appendChild(t)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}if(t?.popular_brands&&t.popular_brands.length>0){const e=document.createElement("div");e.style.cssText=this.getSectionStyle();const n=document.createElement("div");n.style.cssText=this.getSectionTitleStyle(),n.textContent="Popular Brands",e.appendChild(n);const s=document.createElement("div");s.style.cssText=this.getBrandsListStyle(),t.popular_brands.forEach(e=>{const t=document.createElement("div");if(t.style.cssText=this.getBrandItemStyle(),e.logo){const n=document.createElement("img");n.src=e.logo,n.alt=e.name,n.style.cssText=this.getBrandLogoStyle(),n.onerror=()=>{n.style.display="none";const s=document.createElement("span");s.textContent=e.name,s.style.cssText=this.getBrandNameStyle(),t.appendChild(s)},t.appendChild(n)}else{const n=document.createElement("span");n.textContent=e.name,n.style.cssText=this.getBrandNameStyle(),t.appendChild(n)}t.addEventListener("mousedown",t=>{t.preventDefault(),this.options.onBrandClick?this.options.onBrandClick(e.name,e):this.selectSuggestion(e.name)}),t.addEventListener("click",t=>{t.preventDefault(),this.options.onBrandClick?this.options.onBrandClick(e.name,e):this.selectSuggestion(e.name)}),s.appendChild(t)}),e.appendChild(s),this.suggestionsContainer.appendChild(e)}this.updateSuggestionsVisibility()}updateSuggestionsVisibility(){const e=this.richSuggestionsData?.data?.dropdown_recommendations,t=(e?.trending_products?.length??0)>0,n=(e?.trending_searches?.length??0)>0,s=(e?.popular_brands?.length??0)>0,i=this.suggestions.length>0||t||n||s,r=this.input.value.length,o=0===r&&(t||n||s),a=r>=this.options.minQueryLength||this.options.enableRichSuggestions&&o,l=this.isFocused&&this.options.showSuggestions&&a&&i;console.log("👁️ updateSuggestionsVisibility",{isFocused:this.isFocused,hasAnyContent:i,suggestionsCount:this.suggestions.length,hasTrendingProducts:t,hasPopularBrands:s,queryLength:r,isEmptyWithRichData:o,canShow:a,shouldShow:l}),this.suggestionsContainer.style.display=l?"block":"none"}getInputStyle(){const e=this.provider.theme;return`\n flex: 1;\n padding: ${e.spacing.medium};\n font-size: ${e.typography.fontSize.medium};\n font-family: ${e.typography.fontFamily};\n background-color: ${e.colors.background};\n color: ${e.colors.text};\n border: 1px solid ${e.colors.border};\n border-radius: ${"string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium};\n outline: none;\n `}getResponseTimeStyle(){const e=this.provider.theme;return`\n margin-left: ${e.spacing.small};\n font-size: ${e.typography.fontSize.small};\n color: ${e.colors.text};\n opacity: 0.7;\n white-space: nowrap;\n `}getSuggestionsContainerStyle(){const e=this.provider.theme;return`\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n margin-top: ${e.spacing.small};\n background-color: ${e.colors.background};\n border: 1px solid ${e.colors.border};\n border-radius: ${"string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium};\n box-shadow: ${e.shadows.medium};\n max-height: 600px;\n overflow-y: auto;\n z-index: 1000;\n width: 100%;\n `}getSuggestionItemStyle(e){const t=this.provider.theme;return`\n padding: ${t.spacing.medium};\n cursor: pointer;\n background-color: ${e?t.colors.hover:"transparent"};\n color: ${t.colors.text};\n font-family: ${t.typography.fontFamily};\n transition: ${t.transitions?.fast||"150ms ease-in-out"};\n `}getSectionStyle(){const e=this.provider.theme;return`\n padding: ${e.spacing.large||"1.5rem"} ${e.spacing.medium};\n border-bottom: 1px solid ${e.colors.border};\n `}getSectionTitleStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.small};\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n color: ${e.colors.textSecondary||e.colors.text};\n opacity: 0.7;\n margin-bottom: ${e.spacing.medium};\n `}getSuggestionsListStyle(){return"\n display: flex;\n flex-direction: column;\n "}getCountStyle(){const e=this.provider.theme;return`\n opacity: 0.6;\n margin-left: ${e.spacing.small};\n font-size: ${e.typography.fontSize.small};\n `}getProductsGridStyle(){return`\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));\n gap: ${this.provider.theme.spacing.medium};\n max-height: 300px;\n overflow-y: auto;\n `}getProductCardStyle(){const e=this.provider.theme,t="string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium;return`\n display: flex;\n flex-direction: column;\n cursor: pointer;\n border: 1px solid ${e.colors.border};\n border-radius: ${t};\n overflow: hidden;\n transition: ${e.transitions?.fast||"150ms ease-in-out"};\n background-color: ${e.colors.background};\n `}getProductImageStyle(){return"\n width: 100%;\n height: 120px;\n object-fit: cover;\n background-color: #f0f0f0;\n "}getProductInfoStyle(){const e=this.provider.theme;return`\n padding: ${e.spacing.small} ${e.spacing.medium};\n display: flex;\n flex-direction: column;\n gap: ${e.spacing.xsmall??e.spacing.small??"0.25rem"};\n `}getProductTitleStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.small};\n font-weight: 500;\n color: ${e.colors.text};\n line-height: 1.4;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n `}getProductPriceStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.medium};\n font-weight: 600;\n color: ${e.colors.primary||e.colors.text};\n `}getBrandsListStyle(){return`\n display: flex;\n flex-wrap: wrap;\n gap: ${this.provider.theme.spacing.medium};\n max-height: 200px;\n overflow-y: auto;\n `}getBrandItemStyle(){const e=this.provider.theme,t="string"==typeof e.borderRadius?e.borderRadius:e.borderRadius.medium;return`\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n padding: ${e.spacing.small};\n border: 1px solid ${e.colors.border};\n border-radius: ${t};\n transition: ${e.transitions?.fast||"150ms ease-in-out"};\n background-color: ${e.colors.background};\n min-width: 80px;\n min-height: 60px;\n `}getBrandLogoStyle(){return"\n max-width: 60px;\n max-height: 40px;\n object-fit: contain;\n "}getBrandNameStyle(){const e=this.provider.theme;return`\n font-size: ${e.typography.fontSize.small};\n font-weight: 500;\n color: ${e.colors.text};\n text-align: center;\n `}async search(e){void 0!==e&&(this.input.value=e),await this.performSearch()}destroy(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null),this.container.innerHTML=""}},e.SearchLayout=class{constructor(e,t){this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("SearchLayout: container element not found");throw g("SearchLayout: Initialization failed",{error:e.message}),e}this.container=n,this.options={sidebarWidth:t.sidebarWidth||"300px",showSidebarOnMobile:t.showSidebarOnMobile||!1,sidebar:t.sidebar,header:t.header,footer:t.footer},this.render()}render(){if(this.container.innerHTML="",this.container.style.cssText=this.getContainerStyle(),this.options.header&&(this.headerEl="string"==typeof this.options.header?document.querySelector(this.options.header):this.options.header,this.headerEl)){const e=document.createElement("header");e.style.cssText=this.getHeaderStyle(),e.appendChild(this.headerEl.cloneNode(!0)),this.container.appendChild(e)}const e=document.createElement("div");if(e.style.cssText=this.getContentStyle(),this.options.sidebar&&(this.sidebarEl="string"==typeof this.options.sidebar?document.querySelector(this.options.sidebar):this.options.sidebar,this.sidebarEl)){const t=document.createElement("aside");t.style.cssText=this.getSidebarStyle(),t.className=this.getSidebarClass();const n=this.sidebarEl.cloneNode(!0);t.appendChild(n),e.appendChild(t)}if(this.mainEl=document.createElement("main"),this.mainEl.style.cssText=this.getMainStyle(),e.appendChild(this.mainEl),this.container.appendChild(e),this.options.footer&&(this.footerEl="string"==typeof this.options.footer?document.querySelector(this.options.footer):this.options.footer,this.footerEl)){const e=document.createElement("footer");e.style.cssText=this.getFooterStyle(),e.appendChild(this.footerEl.cloneNode(!0)),this.container.appendChild(e)}if(!this.options.showSidebarOnMobile){const e=document.createElement("style");e.textContent="\n @media (max-width: 768px) {\n .search-layout-sidebar-hidden-mobile {\n display: none;\n }\n }\n ",document.head.appendChild(e)}}getMainElement(){return this.mainEl}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n background-color: ${this.theme.colors.background};\n `}getHeaderStyle(){return`\n padding: ${this.theme.spacing.medium};\n border-bottom: 1px solid ${this.theme.colors.border};\n background-color: ${this.theme.colors.background};\n `}getContentStyle(){return`\n display: flex;\n flex: 1;\n gap: ${this.theme.spacing.large};\n padding: ${this.theme.spacing.medium};\n `}getSidebarStyle(){return`\n width: ${this.options.sidebarWidth};\n min-width: ${this.options.sidebarWidth};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n `}getSidebarClass(){return this.options.showSidebarOnMobile?"":"search-layout-sidebar-hidden-mobile"}getMainStyle(){return"\n flex: 1;\n min-width: 0;\n "}getFooterStyle(){return`\n padding: ${this.theme.spacing.medium};\n border-top: 1px solid ${this.theme.colors.border};\n background-color: ${this.theme.colors.background};\n `}},e.SearchManager=class{constructor(e){this.state={results:null,loading:!1,error:null},this.listeners=[],this.client=e.client,this.theme=e.theme||this.getDefaultTheme()}async search(e){this.setState({loading:!0,error:null});try{const{q:t,...n}=e,s="string"==typeof t?t:"",i=await this.client.search(s,n);return this.setState({results:i,loading:!1,error:null}),i}catch(e){const t=e instanceof Error?e:new Error(String(e));return this.setState({results:null,loading:!1,error:t}),null}}clearResults(){this.setState({results:null,error:null})}getState(){return{...this.state}}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}getTheme(){return this.theme}setState(e){this.state={...this.state,...e},this.listeners.forEach(e=>e(this.state))}getDefaultTheme(){return{colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",text:"#212529",border:"#dee2e6",hover:"#f8f9fa",focus:"#007bff",error:"#dc3545"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.25rem"}},spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},borderRadius:{small:"0.25rem",medium:"0.375rem",large:"0.5rem"},shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.12)",medium:"0 3px 6px rgba(0, 0, 0, 0.16)",large:"0 10px 20px rgba(0, 0, 0, 0.19)"}}}},e.SearchProvider=S,e.SearchResults=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n)throw new Error("SearchResults: container element not found");this.container=n,this.options={viewMode:t.viewMode||"list",fieldMapping:t.fieldMapping||{},itemsPerPage:t.itemsPerPage||10,results:t.results,loading:t.loading,error:t.error,onResultClick:t.onResultClick,renderResult:t.renderResult,renderEmpty:t.renderEmpty,renderError:t.renderError},this.container.addEventListener("click",async e=>{const t=e.target,n=t.hasAttribute("data-result-id")?t:t.closest("[data-result-id]");if(n){e.preventDefault(),e.stopPropagation();const s=n.getAttribute("data-result-id"),i=n.getAttribute("data-result-index"),r=i?parseInt(i,10):-1;if(console.log("🔵 SearchResults: Result clicked via delegation",{resultId:s,resultIndex:r,target:t.tagName,resultElement:n}),s&&r>=0){const e=this.extractResults()[r];if(e){const t=this.extractFields(e);if(this.provider.enableAnalytics)try{const e=this.provider.stateManager.getResults(),n=this.provider.stateManager.getState(),i=(n.currentPage-1)*n.itemsPerPage+r+1,o=e?.context||(e?{query:n.query,filters:n.refinements.length>0?n.refinements.map(e=>`${e.field}:${e.value}`).join(" && "):void 0,page:n.currentPage,sortBy:n.sortBy}:void 0);console.log("🔵 SearchResults: Tracking analytics event",{resultId:s,resultIndex:r,absolutePosition:i,currentPage:n.currentPage,itemsPerPage:n.itemsPerPage,hasContext:!!o,searchContext:o}),await this.provider.client.trackEvent({event_name:"product_click",clicked_item_id:s,metadata:{result:t,position:i}},o),console.log("🟢 SearchResults: Analytics event tracked successfully",{resultId:s,position:i})}catch(e){const t=e instanceof Error?e:new Error(String(e));g("SearchResults: Error tracking analytics event",{resultId:s,error:t.message})}if(this.options.onResultClick)try{console.log("🔵 SearchResults: Calling onResultClick callback",{resultId:s,resultIndex:r,extractedResult:t}),this.options.onResultClick(t,r)}catch(e){const t=e instanceof Error?e:new Error(String(e));g("SearchResults: Error in onResultClick callback",{resultId:s,resultIndex:r,error:t.message})}}}}},{passive:!1}),console.log("🔵 SearchResults: Event delegation listener attached to container",{container:this.container}),this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{this.options.results=e.results,this.options.loading=e.loading,this.options.error=e.error,this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.loading&&(this.options.loading=e.loading),void 0!==e.error&&(this.options.error=e.error);const t=this.extractResults().length;c("SearchResults: Updating and re-rendering",{hasResults:!!this.options.results,loading:this.options.loading,hasError:!!this.options.error,resultsCount:t,providedResults:void 0!==e.results,providedLoading:void 0!==e.loading,providedError:void 0!==e.error}),this.render()}render(){if(this.container.innerHTML="",c("SearchResults: Rendering",{hasResults:!!this.options.results,loading:this.options.loading,hasError:!!this.options.error}),this.options.error){const e=this.options.renderError?this.options.renderError(this.options.error):this.renderDefaultError(this.options.error);return void this.container.appendChild(e)}const e=this.extractResults();if(0===e.length){const e=this.options.renderEmpty?this.options.renderEmpty():this.renderDefaultEmpty();return void this.container.appendChild(e)}if("card"===this.options.viewMode||"grid"===this.options.viewMode){const t=document.createElement("div");t.style.cssText=this.getGridContainerStyle(),e.forEach((e,n)=>{const s=this.options.renderResult?this.options.renderResult(this.extractFields(e),n):this.renderDefaultResult(this.extractFields(e),n);t.appendChild(s)}),this.container.appendChild(t)}else e.forEach((e,t)=>{const n=this.options.renderResult?this.options.renderResult(this.extractFields(e),t):this.renderDefaultResult(this.extractFields(e),t);this.container.appendChild(n)})}extractResults(){if(!this.options.results)return c("SearchResults: No results to extract"),[];let e=[];if(Array.isArray(this.options.results))e=this.options.results;else{const t=this.options.results;if(t.results&&Array.isArray(t.results))e=t.results;else if(t.data){const n=t.data;Array.isArray(n)?e=n:n.results&&Array.isArray(n.results)&&(e=n.results)}}return c("SearchResults: Extracted results",{count:e.length,viewMode:this.options.viewMode}),e}extractFields(e){try{const t=this.options.fieldMapping;return{id:r(e,t.id)||String(e.id||""),title:r(e,t.title)||r(e,t.primaryText)||"Untitled",description:r(e,t.description)||r(e,t.secondaryText),image:r(e,t.image)||r(e,t.imageUrl),price:t.price?i(r(e,t.price)):void 0,url:r(e,t.url),metadata:e}}catch(t){const n=t instanceof Error?t:new Error(String(t));return u("SearchResults: Error extracting fields from result",{error:n.message,itemId:e?.id||"unknown"}),{id:String(e?.id||""),title:"Error loading result",metadata:e}}}renderDefaultError(e){const t=document.createElement("div");return t.style.cssText=this.getErrorStyle(),t.textContent=`Error: ${e.message}`,t}renderDefaultEmpty(){const e=document.createElement("div");return e.style.cssText=this.getEmptyStyle(),e.textContent="No results found",e}renderDefaultResult(e,t){const n=document.createElement("div");return n.style.cssText=this.getResultStyle(t),n.setAttribute("data-result-id",e.id),n.setAttribute("data-result-index",String(t)),this.options.onResultClick&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),console.log("SearchResults: Result element created",{resultId:e.id,index:t,element:n,hasOnResultClick:!!this.options.onResultClick}),n.addEventListener("keydown",e=>{if("Enter"===e.key||" "===e.key){e.preventDefault(),e.stopPropagation();const t=new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window});n.dispatchEvent(t)}})),"card"===this.options.viewMode||"grid"===this.options.viewMode?this.renderCardResult(n,e):this.renderListResult(n,e),n}renderCardResult(e,t){if(t.image){const n=document.createElement("div");n.style.cssText=this.getImageContainerStyle();const s=document.createElement("img");s.src=t.image,s.alt=t.title,s.style.cssText=this.getImageStyle(),n.appendChild(s),e.appendChild(n)}const n=document.createElement("div");if(n.style.cssText=this.getCardContentStyle(),t.title){const e=document.createElement("h3");e.style.cssText=this.getTitleStyle(),e.textContent=t.title,n.appendChild(e)}if(t.description){const e=document.createElement("p");e.style.cssText=this.getDescriptionStyle(),e.textContent=t.description,n.appendChild(e)}if(t.price){const e=document.createElement("div");e.style.cssText=this.getPriceStyle(),e.textContent=t.price,n.appendChild(e)}e.appendChild(n)}renderListResult(e,t){if(t.image){const n=document.createElement("img");n.src=t.image,n.alt=t.title,n.style.cssText=this.getListImageStyle(),e.appendChild(n)}const n=document.createElement("div");if(n.style.cssText="flex: 1; min-width: 0;",t.title){const e=document.createElement("h3");e.style.cssText=this.getTitleStyle(),e.textContent=t.title,n.appendChild(e)}if(t.description){const e=document.createElement("p");e.style.cssText=this.getDescriptionStyle(),e.textContent=t.description,n.appendChild(e)}if(t.price){const e=document.createElement("div");e.style.cssText=this.getPriceStyle(),e.textContent=t.price,n.appendChild(e)}e.appendChild(n)}get theme(){return this.provider.theme}getErrorStyle(){return`\n padding: ${this.theme.spacing.large};\n text-align: center;\n color: ${this.theme.colors.error};\n `}getEmptyStyle(){return`\n padding: ${this.theme.spacing.large};\n text-align: center;\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n `}getGridContainerStyle(){return`\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));\n gap: ${this.theme.spacing.medium};\n width: 100%;\n `}getResultStyle(e){const t="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium,n=this.theme.transitions?.normal||"250ms ease-in-out";return"list"===this.options.viewMode?`\n padding: ${this.theme.spacing.medium};\n border-bottom: 1px solid ${this.theme.colors.border};\n border-radius: 0;\n margin-bottom: 0;\n transition: ${n};\n background-color: ${this.theme.colors.background};\n display: flex;\n align-items: flex-start;\n gap: ${this.theme.spacing.medium};\n `:`\n padding: 0;\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${t};\n box-shadow: ${this.theme.shadows.small};\n transition: ${n};\n background-color: ${this.theme.colors.background};\n display: flex;\n flex-direction: column;\n overflow: hidden;\n height: 100%;\n `}getImageContainerStyle(){return`\n width: 100%;\n aspect-ratio: ${"grid"===this.options.viewMode?"1/1":"16/9"};\n overflow: hidden;\n background-color: ${this.theme.colors.hover};\n flex-shrink: 0;\n `}getImageStyle(){return"\n width: 100%;\n height: 100%;\n object-fit: cover;\n "}getCardContentStyle(){return`\n padding: ${this.theme.spacing.medium};\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n `}getListContentStyle(){return`\n display: flex;\n align-items: flex-start;\n gap: ${this.theme.spacing.medium};\n flex: 1;\n min-width: 0;\n `}getListImageStyle(){return`\n width: 100px;\n height: 100px;\n object-fit: cover;\n border-radius: ${"string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium};\n flex-shrink: 0;\n `}getTitleStyle(){return`\n font-size: ${this.theme.typography.fontSize.large};\n font-weight: bold;\n margin: 0;\n margin-bottom: ${this.theme.spacing.small};\n color: ${this.theme.colors.text};\n `}getDescriptionStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n margin: 0;\n margin-bottom: ${this.theme.spacing.small};\n opacity: 0.8;\n `}getPriceStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n font-weight: bold;\n color: ${this.theme.colors.primary};\n margin-top: auto;\n `}},e.SortBy=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("SortBy: container element not found");throw g("SortBy: Initialization failed",{error:e.message}),e}this.container=n,this.currentValue=t.value||t.options[0]?.value||"",this.options={options:t.options,label:t.label,onSortChange:t.onSortChange},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{e.sortBy&&e.sortBy!==this.currentValue&&(this.currentValue=e.sortBy,this.render())}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}update(e){void 0!==e.value&&(this.currentValue=e.value,this.render())}render(){this.container.innerHTML="";const e=document.createElement("div");if(e.style.cssText=this.getContainerStyle(),this.options.label){const t=document.createElement("label");t.textContent=this.options.label,t.style.cssText=this.getLabelStyle(),e.appendChild(t)}const t=document.createElement("select");t.value=this.currentValue,t.style.cssText=this.getSelectStyle(),t.setAttribute("aria-label","Sort results"),t.addEventListener("change",e=>{const t=e.target;if(this.currentValue=t.value,c("SortBy: Sort option changed",{value:t.value}),this.provider.stateManager.setSortBy(t.value),this.options.onSortChange)try{this.options.onSortChange(t.value)}catch(e){const n=e instanceof Error?e:new Error(String(e));g("SortBy: Error in onSortChange callback",{value:t.value,error:n.message})}}),this.options.options.forEach(e=>{const n=document.createElement("option");n.value=e.value,n.textContent=e.label,t.appendChild(n)}),e.appendChild(t),this.container.appendChild(e)}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n `}getLabelStyle(){return`\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n `}getSelectStyle(){const e="string"==typeof this.theme.borderRadius?this.theme.borderRadius:this.theme.borderRadius.medium;return`\n padding: ${this.theme.spacing.small} ${this.theme.spacing.medium};\n font-size: ${this.theme.typography.fontSize.medium};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${e};\n background-color: ${this.theme.colors.background};\n color: ${this.theme.colors.text};\n cursor: pointer;\n outline: none;\n `}},e.Stats=class{constructor(e,t){this.unsubscribeStateManager=null,this.provider=e;const n="string"==typeof t.container?document.querySelector(t.container):t.container;if(!n){const e=new Error("Stats: container element not found");throw g("Stats: Initialization failed",{error:e.message}),e}this.container=n,this.options={showProcessingTime:t.showProcessingTime||!1,results:t.results,loading:t.loading,labels:t.labels},this.unsubscribeStateManager=this.provider.stateManager.subscribe(e=>{this.options.results=e.results,this.options.loading=e.loading,this.render()}),this.render()}destroy(){this.unsubscribeStateManager&&(this.unsubscribeStateManager(),this.unsubscribeStateManager=null)}update(e){void 0!==e.results&&(this.options.results=e.results),void 0!==e.loading&&(this.options.loading=e.loading),this.render()}render(){this.container.innerHTML="";const e=this.getTotalResults();if(null===e)return;const t=document.createElement("div");t.style.cssText=this.getContainerStyle();const n=this.getResultsLabel(e),s=document.createElement("span");if(s.textContent=n,s.style.cssText=this.getResultsStyle(),t.appendChild(s),this.options.showProcessingTime){const e=this.getProcessingTime();if(null!==e){const n=this.getProcessingTimeLabel(e),s=document.createElement("span");s.textContent=n,s.style.cssText=this.getTimeStyle(),t.appendChild(s)}}this.container.appendChild(t)}getTotalResults(){return this.options.results?"number"==typeof this.options.results.totalResults?this.options.results.totalResults:"number"==typeof this.options.results.total?this.options.results.total:this.options.results.results&&Array.isArray(this.options.results.results)?(u("Stats: Using results array length as total (totalResults not found)",{resultsLength:this.options.results.results.length,responseKeys:Object.keys(this.options.results)}),this.options.results.results.length):null:null}getProcessingTime(){if(!this.options.results)return null;const e=this.options.results.processingTimeMs;return"number"==typeof e?e:null}getResultsLabel(e){return this.options.labels?.resultsFound?this.options.labels.resultsFound(e):`${e} result${1!==e?"s":""} found`}getProcessingTimeLabel(e){return this.options.labels?.processingTime?this.options.labels.processingTime(e):` (${e}ms)`}get theme(){return this.provider.theme}getContainerStyle(){return`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.small};\n font-size: ${this.theme.typography.fontSize.medium};\n color: ${this.theme.colors.text};\n `}getResultsStyle(){return`\n font-weight: ${this.theme.typography.fontWeight?.medium||500};\n `}getTimeStyle(){return`\n color: ${this.theme.colors.textSecondary||this.theme.colors.text};\n opacity: 0.7;\n `}},e.createRatingDisplay=function(e,t){return new s(e,t)},e.createTheme=y,e.darkTheme={colors:{primary:"#0d6efd",secondary:"#6c757d",background:"#1a1a1a",text:"#ffffff",border:"#333333",hover:"#2a2a2a",focus:"#0d6efd",error:"#dc3545"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.25rem"}},spacing:{small:"0.5rem",medium:"1rem",large:"1.5rem"},borderRadius:"0.25rem",shadows:{small:"0 1px 3px rgba(0, 0, 0, 0.5), 0 1px 2px rgba(0, 0, 0, 0.7)",medium:"0 3px 6px rgba(0, 0, 0, 0.6), 0 3px 6px rgba(0, 0, 0, 0.8)",large:"0 10px 20px rgba(0, 0, 0, 0.7), 0 6px 6px rgba(0, 0, 0, 0.9)"}},e.defaultTheme=f,e.getHighlightedValue=p,e.getSnippetedValue=function(e){const{attribute:t,hit:n,preTag:s="<mark>",postTag:i="</mark>",fallback:r,maxLength:o=100,ellipsis:a="..."}=e,l=n._snippetResult?.[t]?.value||n.snippet_result?.[t]?.value||n._snippet?.[t]||n.snippet?.[t];let h="";if(h=l?l.replace(/<em>/g,s).replace(/<\/em>/g,i).replace(/<mark>/g,s).replace(/<\/mark>/g,i):p(e),h.length>o){const e=h.substring(0,o),t=e.lastIndexOf(" ");return t>.7*o?e.substring(0,t)+a:e+a}return h},e.highlightQuery=function(e,t,n={}){const{preTag:s="<mark>",postTag:i="</mark>",caseSensitive:r=!1}=n;if(!t||!e)return e;const o=r?"g":"gi",a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${a})`,o);return e.replace(l,`${s}$1${i}`)},e.mergeThemes=(e,...t)=>t.reduce((e,t)=>({colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography,fontSize:{...e.typography?.fontSize,...t.typography?.fontSize}},spacing:{...e.spacing,...t.spacing},borderRadius:t.borderRadius??e.borderRadius,shadows:{...e.shadows,...t.shadows},transitions:{...e.transitions,...t.transitions},breakpoints:{...e.breakpoints,...t.breakpoints},zIndex:{...e.zIndex,...t.zIndex}}),e),e.minimalTheme={colors:{primary:"#000000",secondary:"#666666",background:"#ffffff",text:"#000000",border:"#e0e0e0",hover:"#f5f5f5",focus:"#000000",error:"#cc0000"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{small:"0.875rem",medium:"1rem",large:"1.125rem"}},spacing:{small:"0.5rem",medium:"0.75rem",large:"1rem"},borderRadius:"0",shadows:{small:"none",medium:"none",large:"none"}},e.parseHighlightedParts=function(e,t="<mark>",n="</mark>"){const s=[];let i=e;for(;i.length>0;){const e=i.indexOf(t);if(-1===e){i.length>0&&s.push({value:i,isHighlighted:!1});break}e>0&&s.push({value:i.substring(0,e),isHighlighted:!1});const r=i.substring(e+t.length),o=r.indexOf(n);if(-1===o){s.push({value:i.substring(e),isHighlighted:!1});break}s.push({value:r.substring(0,o),isHighlighted:!0}),i=r.substring(o+n.length)}return s},e.parseQueryHighlightParts=function(e,t,n=!1){if(!t||!e)return[{value:e,isHighlighted:!1}];const s=[],i=n?"g":"gi",r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(r,i);let a,l=0;for(;null!==(a=o.exec(e));)a.index>l&&s.push({value:e.substring(l,a.index),isHighlighted:!1}),s.push({value:a[0],isHighlighted:!0}),l=o.lastIndex;return l<e.length&&s.push({value:e.substring(l),isHighlighted:!1}),s.length>0?s:[{value:e,isHighlighted:!1}]},e.stripHighlightTags=function(e){return e.replace(/<mark>/g,"").replace(/<\/mark>/g,"").replace(/<em>/g,"").replace(/<\/em>/g,"")}});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seekora-ai/ui-sdk-vanilla",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.25",
|
|
4
4
|
"description": "Seekora UI Components SDK for Vanilla JavaScript - Interactive UI components for search and query suggestions",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"@seekora-ai/search-sdk": "^0.2.15"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@seekora-ai/ui-sdk-core": "^0.2.
|
|
46
|
-
"@seekora-ai/ui-sdk-types": "^0.2.
|
|
45
|
+
"@seekora-ai/ui-sdk-core": "^0.2.25",
|
|
46
|
+
"@seekora-ai/ui-sdk-types": "^0.2.25"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@rollup/plugin-commonjs": "^25.0.7",
|