import{getContext as e,store as t}from"@wordpress/interactivity";function r(){const e={credentials:"include"},t="undefined"!=typeof window&&window.wpApiSettings?.nonce;return t&&(e.headers={"X-WP-Nonce":t}),e}const n={};function o(e,t){return t&&0!==Object.keys(t).length?e.filter(e=>{for(const[r,n]of Object.entries(t)){if(""===n||null==n||Array.isArray(n)&&0===n.length)continue;const t=r.indexOf(":"),o=r.slice(0,t),i=r.slice(t+1);if("select"===o){if(String(e[i]??"")!==String(n))return!1}else if("search"===o){const t=String(n).toLowerCase();if(i){if(!String(e[i]??"").toLowerCase().includes(t))return!1}else if(!Object.values(e).some(e=>null!=e&&String(e).toLowerCase().includes(t)))return!1}else if("toggle"===o&&!n.includes(String(e[i]??"")))return!1}return!0}):e}t("gateway/grid",{state:{get data(){return e().data||[]},get records(){return e().records||[]},get loading(){return e().loading||!1},get isNotLoading(){return!e().loading},get error(){return e().error||null},get hasNoError(){return!e().error},get isReady(){return!e().loading&&!e().error},get totalCount(){return(e().data||[]).length},get filteredCount(){return(e().records||[]).length},get hasRecords(){return(e().records||[]).length>0},get isFiltered(){const t=e().filters||{};return Object.values(t).some(e=>""!==e&&null!=e&&(!Array.isArray(e)||e.length>0))}},actions:{filterBySelect:t=>{const r=e(),n=t.target.dataset.fieldKey||"",i=t.target.value;r.filters||(r.filters={}),r.filters[`select:${n}`]=i,r.records=o(r.data,r.filters)},filterBySearch:t=>{const r=e(),n=t.target.dataset.fieldKey||"",i=t.target.value;r.filters||(r.filters={}),r.filters[`search:${n}`]=i,r.records=o(r.data,r.filters)},filterByToggle:t=>{const r=e(),n=t.target.dataset.fieldKey||"",i=t.target.dataset.filterValue||"",s=t.target.checked;r.filters||(r.filters={});const a=`toggle:${n}`,l=Array.isArray(r.filters[a])?r.filters[a]:[];r.filters[a]=s?[...l,i]:l.filter(e=>e!==i),r.records=o(r.data,r.filters)}},callbacks:{init:async()=>{const t=e(),{collectionSlug:o}=t;if(o){t.loading=!0,t.error=null;try{const e=await async function(e){if(n[e])return n[e];const t=await fetch(`/wp-json/gateway/v1/collections/${e}`,r());if(!t.ok)throw new Error(`[Gateway Grid] Failed to load collection info (${t.status} ${t.statusText})`);const o=await t.json();return n[e]=o,o}(o),i=e.routes?.endpoint;if(!i)throw new Error(`[Gateway Grid] No REST endpoint found for collection "${o}".`);const s=await fetch(i,r());if(!s.ok)throw new Error(`[Gateway Grid] Failed to load records (${s.status} ${s.statusText})`);const a=await s.json(),l=a.data?.items??a.items??a??[];t.data=l,t.records=[...l],t.filters={},t.loading=!1}catch(e){console.error("[Gateway Grid] Init error:",e),t.error=e.message,t.loading=!1}}else console.warn("[Gateway Grid] No collectionSlug set. Add a collection via the block settings panel.")}}});