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