(()=>{class e{constructor(){this.formController=null,this.tabsInstance=null,this.queue=window.jvbQueue,this.a11y=window.jvbA11y,this.init()}init(){if(window.jvbForm&&!window.formController?(this.formController=new window.jvbForm,window.formController=this.formController):window.formController&&(this.formController=window.formController),window.jvbTabs){const e=document.querySelector(".jvb-seo-admin");e&&(this.tabsInstance=new window.jvbTabs(e))}this.formController&&this.formController.subscribe(((e,t)=>{"form-submit"===e&&this.handleFormSubmit(t)})),this.queue&&this.queue.subscribe(((e,t)=>{Object.hasOwn(t,"endpoint")&&"seo"===t.endpoint&&("operation-completed"===e?this.handleQueueSuccess(e,t):"operation-failed-permanent"===e&&this.handleQueueFailure(e,t))})),this.initializeForms(),this.addPreservedFieldStyles()}initializeForms(){document.querySelectorAll('form[data-save="seo"]').forEach((e=>{this.formController&&this.formController.registerForm(e,{endpoint:"seo",autosave:!1,formStatus:!1}),this.initializeTypeSwitch(e);const t=e.querySelector('[data-action="reset"]');t&&t.addEventListener("click",(()=>this.handleReset(e)))}))}handleFormSubmit(e){const t=e.config.element.dataset.content,n=e.fullData,o={endpoint:"seo",headers:{"X-WP-Nonce":window.auth.getNonce()},data:{context:t,action:"save",...n},popup:"Saving SEO configuration",title:`Saving ${t} settings`};this.queue.addToQueue(o)}async handleReset(e){const t=e.dataset.content;if(!confirm("Reset to default settings? This cannot be undone."))return;const n={endpoint:"seo",headers:{"X-WP-Nonce":window.auth.getNonce()},data:{context:t,action:"reset"},popup:"Resetting configuration",title:`Resetting ${t} to defaults`};this.queue.addToQueue(n)}handleQueueSuccess(e,t){console.log("SEO save successful:",t),this.a11y&&"function"==typeof this.a11y.announce&&this.a11y.announce("Configuration saved successfully"),"reset"===t.operation?.data?.action&&t.response?.schema&&this.reloadFormData(t.operation.data.context,t.response)}handleQueueFailure(e,t){console.error("SEO operation failed permanently:",t),this.a11y&&"function"==typeof this.a11y.announce&&this.a11y.announce(`Error: ${t.error_message||"Operation failed"}`)}reloadFormData(e,t){const n=document.querySelector(`form[data-content="${e}"]`);if(!n)return;const o=t.schema||{};Object.keys(o).forEach((e=>{const t=n.querySelector(`[name="${e}"]`);t&&("checkbox"===t.type?t.checked=!!o[e]:t.value=o[e]||"")})),this.a11y&&"function"==typeof this.a11y.announce&&this.a11y.announce("Form reset to defaults")}initializeTypeSwitch(e){const t=e.querySelector('select[name="type"]');t&&(t.addEventListener("change",(n=>{const o=e.dataset.currentType||t.dataset.initialValue,a=n.target.value;o!==a&&this.confirmTypeChange(e,t,o,a)})),t.dataset.initialValue=t.value,e.dataset.currentType=t.value)}confirmTypeChange(e,t,n,o){const a={},s=new FormData(e);for(let[e,t]of s.entries())"type"!==e&&t&&""!==t&&(a[e]=t);const r=window.getTemplate(`seo-${o}`);if(!r)return console.error("No template found for type:",o),void(t.value=n);const i=e=>e.split(":")[0],l=new Set(Object.keys(a).map(i)),c=r.querySelectorAll("[data-field]"),u=new Set(Array.from(c).map((e=>e.dataset.field)));if(0===u.size){const e=r.querySelectorAll("[name]");Array.from(e).forEach((e=>{u.add(i(e.getAttribute("name")))}))}const d=[...l].filter((e=>u.has(e))),h=[...l].filter((e=>!u.has(e)));let p=`Change schema type from ${n} to ${o}?\n\n`;d.length>0&&(p+=`✓ ${d.length} field value(s) will be preserved:\n`,p+=d.map((e=>` • ${e}`)).join("\n"),p+="\n\n"),h.length>0&&(p+=`⚠ ${h.length} field value(s) will be lost:\n`,p+=h.map((e=>` • ${e}`)).join("\n")),confirm(p)?this.handleTypeChange(e,t,o):(t.value=n,this.a11y&&"function"==typeof this.a11y.announce&&this.a11y.announce("Type change cancelled"))}handleTypeChange(e,t,n){const o=e.dataset.currentType||t.dataset.initialValue,a=this.collectFormData(e),s=window.getTemplate(`seo-${n}`);if(!s)return void console.error("No template found for type:",n);const r=e.querySelector(".seo-"+o);if(r&&(r.parentNode.insertBefore(s,r),r.remove()),e.dataset.currentType=n,window.jvbPopulateForm){const t=new window.jvbPopulateForm,o=[];if(Object.keys(a).forEach((n=>{const s=e.querySelector(`[data-field="${n}"]`);if(s){const e=this.getFieldType(s),r=a[n];if("repeater"===e&&Array.isArray(r))t.populateRepeaterField(s,n,r),o.push(n);else if(null!=r&&""!==r){const e=s.querySelector(`[name="${n}"]`)||s.querySelector(`[name^="${n}"]`);e&&(this.populateSimpleField(e,r),o.push(n))}}})),o.length>0){const e=`Schema type changed to ${n}. Preserved ${o.length} field value(s).`;console.log(e),this.a11y&&"function"==typeof this.a11y.announce&&this.a11y.announce(e)}else{const e=`Schema type changed to ${n}.`;this.a11y&&"function"==typeof this.a11y.announce&&this.a11y.announce(e)}}}collectFormData(e){const t={},n=new FormData(e);for(let[e,o]of n.entries())if("type"!==e&&"context"!==e)if(e.includes(":")){const n=e.split(":"),a=n[0],s=parseInt(n[1]),r=n[2];t[a]||(t[a]=[]),t[a][s]||(t[a][s]={}),t[a][s][r]=o}else t[e]=o;return t}getFieldType(e){return e.classList.contains("repeater")?"repeater":"text"}populateSimpleField(e,t){"checkbox"===e.type?e.checked="1"===t||"true"===t||!0===t:"SELECT"===e.tagName?setTimeout((()=>{e.value=t}),10):e.value=t,e.classList.add("value-preserved"),setTimeout((()=>e.classList.remove("value-preserved")),2e3)}addPreservedFieldStyles(){const e=document.createElement("style");e.textContent="\n .value-preserved {\n background-color: #e7f5e7 !important;\n transition: background-color 0.3s ease;\n }\n ",document.head.appendChild(e)}}document.addEventListener("DOMContentLoaded",(async function(){window.auth.subscribe((t=>{"auth-loaded"===t&&(window.jvbSchema=new e)}))}))})();