import{useCallback as C,useEffect as I,useState as F,useRef as L}from"react";import{SEARCH_DEBOUNCE_TIME_MS as G}from"@redocly/theme/core/constants";import{withPathPrefix as _}from"@redocly/theme/core/utils";import{SEARCH_GROUP_FACET_FIELD as b,SEARCH_PRODUCT_FIELD as N,SEARCH_VERSION_FIELD as k,ServerRoutes as O}from"../../../constants/index.js";import{useGlobalData as U,useI18nConfig as P}from"../hooks";import{debounce as x}from"../../../shared/jsUtils";import{usePageVersions as J}from"../../providers/page-data/hooks";import{useFacets as M}from"./useFacets";import{otelTelemetry as Q}from"../telemetry/otel/telemetry";const B=(t,o,e,n,a,r,i,l)=>{const{currentLocale:d}=P(),h=L(""),m=C(x(async(c,f,S,u)=>{if(!c.trim().length&&!f.length){e({}),n({}),a(!1);return}const E={method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:c,filter:A(f,u,r),locale:S})};try{const p=await fetch(_(O.SEARCH),E);if(h.current===c){const s=await p.json();n(s.facets),e(s.documents),c.trim().length>1&&Q.send({type:"search.query",payload:{query:c,result_count:Object.keys(s.documents).length.toString()}})}a(!1)}catch(p){e({}),console.log(p)}},G),[r?.version,r?.folderId,i]);return I(()=>{l||(a(!0),m(t,o,d,i),h.current=t)},[l,o,d,i,t,m,a]),{}},K=(t,o,e,n,a,r,i,l)=>{const{currentLocale:d}=P();I(()=>{h(e,t,o,d,n,a,l)},[n,l]);const h=C(async(m,c,f,S,u,E,p)=>{if(u){const{groupKey:s}=u;i(!0);const v={method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:c,filter:(()=>{const R=E.find(y=>y.field===b);return R&&!f.find(w=>w.field===R?.field)?[...f,{field:R.field,values:[s]}]:A(f,p)})(),loadMore:u,locale:S})},D=await(await fetch(_(O.SEARCH),v)).json(),H=m[s]||[],T=D.documents[s],j={...m,[s]:[...H,...T]};r(j),i(!1)}},[]);return{}};function se(t,o){const{searchFeatures:e}=U(),[n,a]=F(""),[r,i]=F([]),[l,d]=F({}),[h,m]=F({}),[c,f]=F(),[S,u]=F(!1),{facets:E}=M(h),{versions:p=[]}=J()||{},s=p.find(g=>g?.active);return B(n,r,d,m,u,s,t,o),K(n,r,l,c,E,d,u,t),{query:n,setQuery:a,filter:r,setFilter:i,items:l,isSearchLoading:S,facets:E,groupField:b,setLoadMore:f,advancedSearch:e?.advanced?.enabled,askAi:e?.ai?.enabled}}function A(t,o,e){return[...t,...o?[{field:N,values:[o]}]:[],...e?[{field:k,values:[...e.default?["default"]:[e.folderId,e.version]]}]:[]]}export{se as useSearch};
