function e(e,a){return e instanceof l?e.response?.message??e.message:e instanceof Error?e.message:a}import{r as a}from"./vendor-react.DHNfi5sm.js";import{e as t}from"./platform-auth-core.BUbnZ-vn.js";import{f as i,l as s,a as r,X as l}from"./platform-core.tlhrBXt0.js";const o={},n={get(e){const a=o[e];return a?Date.now()-a.timestamp>6e4?(delete o[e],null):{capabilities:a.capabilities,loading:a.loading}:null},set(e,a,t){o[e]={capabilities:a,loading:t,timestamp:Date.now()}},setLoading(e,a){o[e]&&(o[e].loading=a)},clear(e){e?delete o[e]:Object.keys(o).forEach(e=>delete o[e])}},c=l=>{const o=n.get(l),[c,u]=a.useState(o?.capabilities||[]),[d,p]=a.useState(o?.loading||!1),[f,b]=a.useState(null);a.useEffect(()=>{const e=n.get(l);e&&e.capabilities.length!==c.length&&(u(e.capabilities),p(e.loading))},[l,c]);const m=a.useRef(null),g=a.useCallback(async()=>{p(!0),b(null);try{const e=await i.get("/wp-json/fleekdash/v1/roles"),a=Array.isArray(e?.data)?e.data:[];if(0===a.length){const e="Failed to load roles from API";return s("AUTH",`[useRoleCapabilities] ${e}`),void b(e)}const t=a.find(e=>e?.id===l);if(!t){const e=`Role '${l}' not found`;return r("AUTH",`[useRoleCapabilities] ${e}`),void b(e)}const o=t.capabilities??[],c=Array.from(new Set(function(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):null!=e&&"object"==typeof e?Object.keys(e).filter(a=>Boolean(e?.[a])):[]}(o))).sort((e,a)=>e.localeCompare(a));u(c),n.set(l,c,!1)}catch(a){const t=e(a,"Unknown error occurred");s("AUTH",`[useRoleCapabilities] Error loading capabilities for role ${l}:`,a),b(t)}finally{p(!1)}},[l]),y=a.useCallback(e=>!e||""===e.trim()||!d&&c.includes(e),[c,d]),C=a.useCallback(async a=>{if(c.includes(a))return!0;try{const e=[...c,a],r=await i.put(`/wp-json/fleekdash/v1/roles/${l}`,{capabilities:e});return!1===r?.success?(s("AUTH",`[useRoleCapabilities] Failed to add capability '${a}' to role ${l}:`,r?.message),!1):(u(e),n.set(l,e,!1),t({role:l,added:[a],removed:[]}),m.current=null,!0)}catch(r){const t=e(r,"Unknown error");return s("AUTH",`[useRoleCapabilities] Error adding capability '${a}' to role ${l}:`,t),!1}},[l,c]),h=a.useCallback(async a=>{if(!c.includes(a))return!0;try{const e=c.filter(e=>e!==a),r=await i.put(`/wp-json/fleekdash/v1/roles/${l}`,{capabilities:e});return!1===r?.success?(s("AUTH",`[useRoleCapabilities] Failed to remove capability '${a}' from role ${l}:`,r?.message),!1):(u(e),n.set(l,e,!1),t({role:l,added:[],removed:[a]}),m.current=null,!0)}catch(r){const t=e(r,"Unknown error");return s("AUTH",`[useRoleCapabilities] Error removing capability '${a}' from role ${l}:`,t),!1}},[l,c]),A=a.useCallback(async()=>{m.current=null,await g()},[g]);return a.useEffect(()=>{if(l){const e=n.get(l);e&&0!==e.capabilities.length||g()}},[l,g]),{capabilities:c,isLoading:d,error:f,hasCapability:y,refreshCapabilities:A,addCapability:C,removeCapability:h}};export{c as u};
//# sourceMappingURL=platform-role-capabilities.CNayiot6.js.map
