import{o as e}from"./rolldown-runtime-BTPm5ob3.js";import{r as t}from"./animations-BBry1XJJ.js";import{u as n}from"./vendor-DE5lxjzu.js";var r=e(t(),1);function i({rootData:e,moduleData:t,initialSettings:i,settingsPayloadKey:a,autoSaveDelay:o=1500,onBeforeSave:s,onAfterSave:c}){let[l,u]=(0,r.useState)(()=>({...i,...t?.options||{}})),[d,f]=(0,r.useState)(`idle`),[p,m]=(0,r.useState)(!1),[h,g]=(0,r.useState)(!1),_=(0,r.useMemo)(()=>({...e?.i18n||{},...t?.i18n||{}}),[e?.i18n,t?.i18n]),v=(0,r.useRef)(!0),[y,b]=(0,r.useState)(t);t!==y&&(b(t),t?.options&&JSON.stringify(t.options)!==JSON.stringify(y?.options)&&u(e=>({...e,...t.options})));let x=(0,r.useCallback)((e,n)=>{u(r=>{let i={...r,[e]:n},a=t?.optionNames||{},o=a[e];if(o)i[o]=n;else{let t=Object.keys(a).find(t=>a[t]===e);t&&(i[t]=n)}return i}),g(!0)},[t]),S=(0,r.useCallback)(async r=>{let i=typeof r==`boolean`?r:!1,o=typeof r==`object`?r:l;i||m(!0),f(`saving`);try{let r={},l=s?s(o):o;Object.keys(l).forEach(e=>{let n=(t?.optionNames||{})[e]||e,i=l[e];typeof i==`boolean`&&(i=+!!i),r[n]=i});let u=a?{settings:{[a]:r}}:{settings:r},d=await fetch(`${e?.global?.settingsRestUrl}?_=${Date.now()}`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-WP-Nonce":e?.global?.wpRestNonce||``},body:JSON.stringify(u)});if(!d.ok)throw Error(`Server responded with ${d.status}`);let p=await d.json();g(!1),f(`saved`),window.dispatchEvent(new CustomEvent(`wawp-refresh-data`)),i||n.success(_.settingsSaved||`Settings saved successfully`),c&&c(p),setTimeout(()=>f(`idle`),3e3)}catch(e){f(`error`);let t=e instanceof Error?e.message:String(e);i||n.error(t||_.errorOccurred||`An error occurred`),console.error(`Save error:`,e)}finally{i||m(!1)}},[e,t,l,a,_,s,c]);return(0,r.useEffect)(()=>{if(v.current){v.current=!1;return}if(!h)return;let e=setTimeout(()=>{S(!0)},o);return()=>clearTimeout(e)},[l,h,S,o]),(0,r.useEffect)(()=>{let e=e=>{h&&(e.preventDefault(),e.returnValue=``)};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[h]),{settings:l,setSettings:u,updateSetting:x,handleSave:S,saveStatus:d,hasUnsavedChanges:h,setHasUnsavedChanges:g,isSaving:p,t:_}}export{i as t};