import{useCallback as h,useEffect as w,useMemo as y,useState as P}from"react";import{useSearchParams as Q}from"react-router-dom";import{telemetry as C}from"../../telemetry/index.js";import{parseFilterQuery as g,formatFilterQuery as U,collectFilterOptions as b}from"../../../utils";function O(r){return r instanceof Set?r.size>0:!!(r?.from||r?.to)}function k(r,d){const[u,m]=Q(),i=u.get("filter")||"",[o,f]=P(()=>g(i,r?.filters||[])),p=y(()=>b(r?.filters,d),[r?.filters,d]);w(()=>{const t=r?.filters||[];if(t.length>0&&o.length!==t.length){const e=g(i,t);f(e)}},[r?.filters,o.length,i]);const F=h((t,e)=>{f(l=>l.map((s,c)=>{if(c!==t||!(s instanceof Set))return s;const n=new Set(s);return n.has(e)?n.delete(e):n.add(e),n})),window.scrollTo(0,0)},[]),S=h((t,e)=>{f(l=>l.map((a,s)=>s!==t?a:a instanceof Set?e&&typeof e=="string"?new Set([e]):new Set:{from:typeof e=="object"?e?.from:void 0,to:typeof e=="object"?e?.to:void 0})),C.sendCatalogFilterChangedMessage({type:"select"}),window.scrollTo(0,0)},[]);return w(()=>{const t=new URLSearchParams(u),e=U(o,r?.filters||[]);e?t.set("filter",e):t.delete("filter"),m(t,{replace:!0})},[r?.filters,o,u,m]),y(()=>{const t=p.map((l,a)=>{const s=o[a],c=O(s);return{...l,toggleOption:n=>F(a,n),selectOption:n=>S(a,n),selectedOptions:s??new Set,isFilterUsed:c}});return{filters:t.map(l=>{const a=t.findIndex(n=>n.property===l.parentFilter),s=o[a],c=l.parentFilter?O(s):!0;return{...l,parentUsed:c}}),filterQuery:i}},[p,o,F,S,i])}export{k as useCatalogFilter};
