(() => {
  "use strict";
  const workspace = document.querySelector("[data-h4bs-form-workspace]");
  const deleteForms = document.querySelectorAll("[data-h4bs-delete-form]");
  deleteForms.forEach((form) => form.addEventListener("submit", (event) => {
    const expected = form.dataset.formName || "";
    const actual = form.querySelector("[name=confirm_name]")?.value.trim() || "";
    if (!expected || expected !== actual) { event.preventDefault(); form.querySelector("[name=confirm_name]")?.setCustomValidity("Type the exact form name to continue."); form.reportValidity(); }
  }));
  document.querySelectorAll("[data-h4bs-copy-shortcode]").forEach((button) => button.addEventListener("click", async () => {
    const shortcode = button.dataset.shortcode || "";
    if (!shortcode) return;
    try {
      await navigator.clipboard.writeText(shortcode);
      button.textContent = "Copied";
      button.setAttribute("aria-label", "Embed code copied");
    } catch (_) {
      const selection = window.getSelection();
      const code = button.closest(".h4bs-form-more-panel")?.querySelector("code");
      if (selection && code) { const range=document.createRange(); range.selectNodeContents(code); selection.removeAllRanges(); selection.addRange(range); }
      button.textContent = "Select code to copy";
    }
  }));
  if (!workspace) return;
  const form = workspace.querySelector("[data-h4bs-form-editor]");
  const fieldList = workspace.querySelector("[data-h4bs-field-list]");
  const schema = workspace.querySelector("#h4bs-form-fields");
  const raw = workspace.querySelector("[data-h4bs-raw-schema]");
  const preview = workspace.querySelector("[data-h4bs-form-preview]");
  const status = workspace.querySelector("[data-h4bs-field-status]");
  const saveState = workspace.querySelector("[data-h4bs-save-state]");
  const saveButton = workspace.querySelector("[data-h4bs-save]");
  const saveBar = saveButton.closest(".h4bs-form-savebar");
  const conflictPanel = document.createElement("div");
  conflictPanel.className = "notice notice-warning inline h4bs-form-conflict";
  conflictPanel.setAttribute("role", "alert");
  conflictPanel.hidden = true;
  conflictPanel.innerHTML = '<h2>Review newer changes</h2><p><strong>Another person saved a newer version.</strong> Your entries are still in this browser. Copy your work before comparing it with the latest version.</p><p><button type="button" class="button" data-h4bs-copy-draft>Copy my form data</button> <a class="button" target="_blank" rel="noopener" data-h4bs-open-latest>Open latest in a new tab</a></p>';
  saveBar.after(conflictPanel);
  const isNew = () => Number(form.querySelector("[name=id]")?.value || 0) === 0;
  let fields = [];
  let schemaInvalid = workspace.dataset.h4bsSchemaValid === "0";
  try { fields = JSON.parse(schema.value || "[]"); } catch (_) { fields = []; schemaInvalid = true; }
  if (!Array.isArray(fields)||fields.some((field)=>!field||typeof field!=="object"||Array.isArray(field))) { fields = []; schemaInvalid = true; }
  if (!fields.length && Number(form.querySelector("[name=id]")?.value || 0) === 0) fields = [
    {key:"name",label:"Name",type:"text",required:"1",placeholder:"",options:"",default:"",width:"50"},
    {key:"email",label:"Email",type:"email",required:"1",placeholder:"",options:"",default:"",width:"50"},
    {key:"message",label:"How can we help?",type:"textarea",required:"1",placeholder:"",options:"",default:"",width:"100"},
  ];
  let saved = JSON.stringify(fields);
  let metaSaved = "";
  let fieldHistory = [];
  let dragged = -1;
  let lastChangedKey = "";
  const knownTypes = new Set(["text","email","tel","url","textarea","select","checkbox","hidden","date","time","number"]);
  const isRequired = (field) => field.required === true || field.required === 1 || field.required === "1";
  const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"}[char]));
  const keyFor = (label) => String(label || "question").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,48) || `question_${Date.now()}`;
  const rawEditor = document.createElement("textarea"); rawEditor.rows=10; rawEditor.className="large-text code"; rawEditor.setAttribute("aria-label","Raw field data"); rawEditor.value=schema.value; raw?.replaceWith(rawEditor);
  const sync = () => { if (schemaInvalid) return; schema.value = JSON.stringify(fields); rawEditor.value = JSON.stringify(fields, null, 2); };
  const metaSnapshot = () => JSON.stringify(Array.from(new FormData(form).entries()).filter(([key]) => !["h4bs_form_nonce","request_id","fields_json"].includes(key)));
  const isDirty = () => isNew() || JSON.stringify(fields) !== saved || metaSnapshot() !== metaSaved;
  const defaultValidationError=(field)=>{const value=String(field.default||"").trim();if(value==="")return "";if(field.type==="number"&&!Number.isFinite(Number(value)))return `Default answer for ${field.label||field.key} must be a number.`;if(field.type==="date"&&!/^\d{4}-\d{2}-\d{2}$/.test(value))return `Default answer for ${field.label||field.key} must use YYYY-MM-DD.`;if(field.type==="time"&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(value))return `Default answer for ${field.label||field.key} must use 24-hour HH:MM.`;if(field.type==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value))return `Default answer for ${field.label||field.key} must be an email address.`;if(field.type==="url"){try{const url=new URL(value);if(!["http:","https:"].includes(url.protocol))throw new Error();}catch(_){return `Default answer for ${field.label||field.key} must be an http or https address.`;}}if(field.type==="select"&&!String(field.options||"").split(/[|,\n]/).map((item)=>item.trim()).includes(value))return `Default answer for ${field.label||field.key} must be one of its choices.`;return "";};
  const fieldValidationError=()=>{if(fields.length===0)return "Add at least one question before saving.";if(fields.length>60)return "This form has more than 60 questions. Nothing will be truncated; remove extra questions or ask support to split the form.";const keys=fields.map((field)=>String(field.key||""));if(keys.some((key)=>!/^[A-Za-z0-9_-]+$/.test(key)))return "Every question needs a unique internal key using only letters, numbers, dashes, or underscores.";if(new Set(keys).size!==keys.length)return "Two questions use the same internal key. Open More question settings and make each key unique.";for(const field of fields){const error=defaultValidationError(field);if(error)return error;}return "";};
  const markDirty = () => { sync(); const dirty = isDirty(); const fieldError=fieldValidationError(); const blocked=schemaInvalid||fieldError!=="";saveState.textContent = schemaInvalid ? "Saving blocked — repair field data" : (fieldError|| (dirty ? "Unsaved changes" : "All changes saved")); saveButton.disabled = blocked || !dirty; saveBar.hidden = !dirty && !blocked;if(fieldError)announce(fieldError); };
  const remember = () => { fieldHistory.push(structuredClone(fields)); if (fieldHistory.length > 30) fieldHistory.shift(); const undo = workspace.querySelector("[data-h4bs-undo]"); undo.hidden = fieldHistory.length === 0; };
  const announce = (message) => { status.textContent = ""; requestAnimationFrame(() => { status.textContent = message; }); };
  const renderPreview = () => {
    preview.innerHTML = fields.filter((f) => f.type !== "hidden").map((field) => {
      const label = esc(field.label || field.key || "Question"); const required = isRequired(field) ? " <span aria-hidden=\"true\">*</span>" : "";
      const span=String(field.width||"100")==="25"?3:String(field.width||"100")==="33"?4:String(field.width||"100")==="50"?6:String(field.width||"100")==="66"?8:String(field.width||"100")==="75"?9:12;const style=` style="grid-column:span ${span}"`;
      if (field.type === "textarea") return `<div class="h4bs-preview-field"${style}><label>${label}${required}</label><textarea disabled>${esc(field.default||"")}</textarea></div>`;
      if (field.type === "select") {const choices=String(field.options||"").split(/[|,\n]/).map((item)=>item.trim()).filter(Boolean);return `<div class="h4bs-preview-field"${style}><label>${label}${required}</label><select disabled>${choices.map((item)=>`<option${item===String(field.default||"")?" selected":""}>${esc(item)}</option>`).join("")||"<option>Choose one</option>"}</select></div>`;}
      if (field.type === "checkbox") return `<div class="h4bs-preview-field"${style}><label><input type="checkbox" disabled${["1","true","yes","on"].includes(String(field.default||"").toLowerCase())?" checked":""}> ${label}${required}</label></div>`;
      const previewDefault=defaultValidationError(field)===""?field.default||"":"";return `<div class="h4bs-preview-field"${style}><label>${label}${required}</label><input type="${knownTypes.has(field.type) ? esc(field.type) : "text"}" disabled placeholder="${esc(field.placeholder||"")}" value="${esc(previewDefault)}"></div>`;
    }).join("") + `<button class="button button-primary" type="button" disabled>${esc(form.querySelector("[name=button_label]")?.value || "Submit")}</button>`;
  };
  const render = (focusKey = "") => {
    fieldList.innerHTML = "";
    if (!fields.length) fieldList.innerHTML = '<div class="h4bs-empty-help"><strong>No questions yet.</strong><p>Add the first question visitors should answer.</p></div>';
    fields.forEach((field, index) => {
      const card = document.createElement("article"); card.className = "h4bs-field-card"; card.draggable = true; card.dataset.index = String(index); card.dataset.key = String(field.key || "");
      const type = String(field.type || "text"); const legacy = !knownTypes.has(type);
      card.innerHTML = `<div class="h4bs-field-summary"><span class="h4bs-drag" aria-hidden="true" title="Drag to reorder">⋮⋮</span><div class="h4bs-field-name"><strong>${esc(field.label || "Untitled question")}</strong><span>${esc(legacy ? `Legacy field (${type})` : type)}${isRequired(field) ? " · Required" : ""}</span></div><button type="button" class="button h4bs-move-up" aria-label="Move ${esc(field.label||"question")} up">↑</button><button type="button" class="button h4bs-move-down" aria-label="Move ${esc(field.label||"question")} down">↓</button><div class="h4bs-field-secondary"><button type="button" class="button h4bs-duplicate">Duplicate</button><button type="button" class="button h4bs-edit" aria-expanded="false">Edit question</button></div></div><div class="h4bs-field-editor" hidden><label>Question label<input data-prop="label" value="${esc(field.label||"")}"></label><label>Answer type<select data-prop="type" ${legacy ? "disabled" : ""}>${["text","email","tel","url","textarea","select","checkbox","date","time","number","hidden"].map((v)=>`<option value="${v}"${v===type?" selected":""}>${v}</option>`).join("")}</select>${legacy ? '<span class="description">This extension field is preserved unchanged. Use Advanced data or its extension to edit it.</span>' : ""}</label><label>Help or placeholder text<input data-prop="placeholder" value="${esc(field.placeholder||"")}"></label><label class="h4bs-options"${["select","checkbox"].includes(type) ? "" : " hidden"}>Choices (one per line)<textarea data-prop="options" rows="3">${esc(field.options||"")}</textarea></label><label class="h4bs-check"><input type="checkbox" data-prop="required"${isRequired(field) ? " checked" : ""}> Answer required</label><div class="h4bs-field-wide"><button type="button" class="button button-link-delete h4bs-remove">Remove question</button></div></div>`;
      card.querySelector(".h4bs-move-up").disabled = index === 0;
      card.querySelector(".h4bs-move-down").disabled = index === fields.length - 1;
      if (!legacy) {
        const advanced = document.createElement("details");
        advanced.className="h4bs-field-advanced h4bs-field-wide";
        const choices=String(field.options||"").split(/[|,\n]/).map((item)=>item.trim()).filter(Boolean);const defaultControl=type==="select"?`<select data-prop="default"><option value="">No default</option>${choices.map((item)=>`<option value="${esc(item)}"${item===String(field.default||"")?" selected":""}>${esc(item)}</option>`).join("")}</select>`:type==="checkbox"?`<label class="h4bs-check"><input type="checkbox" data-prop="default"${["1","true","yes","on"].includes(String(field.default||"").toLowerCase())?" checked":""}> Checked by default</label>`:`<input type="text" ${type==="number"?'inputmode="decimal" ':""}data-prop="default" value="${esc(field.default||"")}">`;
        advanced.innerHTML=`<summary>More question settings</summary><div class="h4bs-field-advanced-grid"><label>Internal key <input data-prop="key" value="${esc(field.key||"")}"><span class="description">Expert setting used by integrations. Avoid changing it after launch.</span></label><label>Answer width <select data-prop="width">${[["25","Quarter row"],["33","One third"],["50","Half row"],["66","Two thirds"],["75","Three quarters"],["100","Full row"]].map(([value,text])=>`<option value="${value}"${String(field.width||"100")===value?" selected":""}>${text}</option>`).join("")}</select></label><label>Default answer ${defaultControl}<span class="description">Optional starting value visitors may replace.</span></label></div>`;
        card.querySelector(".h4bs-field-wide")?.before(advanced);
      }
      fieldList.append(card);
    });
    sync(); renderPreview();
    if (focusKey) fieldList.querySelector(`[data-key="${CSS.escape(focusKey)}"] .h4bs-edit`)?.focus();
  };
  const move = (from, to) => { if (to < 0 || to >= fields.length || from === to) return; remember(); const [item] = fields.splice(from,1); fields.splice(to,0,item); lastChangedKey=String(item.key||""); render(item.key); markDirty(); announce(`Moved ${item.label || "question"} to ${to + 1} of ${fields.length}.`); };
  fieldList.addEventListener("click", (event) => {
    const card = event.target.closest(".h4bs-field-card"); if (!card) return; const index = Number(card.dataset.index);
    if (event.target.closest(".h4bs-edit")) { const editor = card.querySelector(".h4bs-field-editor"); const open = editor.hidden; editor.hidden = !open; event.target.setAttribute("aria-expanded", String(open)); if (open) editor.querySelector("input,select,textarea")?.focus(); }
    else if (event.target.closest(".h4bs-move-up")) move(index,index-1);
    else if (event.target.closest(".h4bs-move-down")) move(index,index+1);
    else if (event.target.closest(".h4bs-duplicate")) { remember(); const copy = structuredClone(fields[index]); copy.key = `${copy.key || "question"}_copy_${Date.now()}`; copy.label = `${copy.label || "Question"} copy`; lastChangedKey=copy.key; fields.splice(index+1,0,copy); render(copy.key); markDirty(); announce(`Duplicated ${fields[index].label || "question"}.`); }
    else if (event.target.closest(".h4bs-remove")) { remember(); const removed = fields.splice(index,1)[0]; lastChangedKey=String(removed.key||""); render(); markDirty(); workspace.querySelector("[data-h4bs-undo]")?.focus(); announce(`Removed ${removed.label || "question"}. Use Undo to restore it before saving.`); }
  });
  fieldList.addEventListener("focusin",(event)=>{const card=event.target.closest(".h4bs-field-card");if(!card||!event.target.dataset.prop||event.target.dataset.h4bsUndoStarted)return;remember();lastChangedKey=card.dataset.key;event.target.dataset.h4bsUndoStarted="1";});
  fieldList.addEventListener("focusout",(event)=>{if(event.target.dataset.prop)delete event.target.dataset.h4bsUndoStarted;});
  fieldList.addEventListener("change", (event) => { const card=event.target.closest(".h4bs-field-card"); const prop=event.target.dataset.prop; if(!card||!prop)return; const field=fields[Number(card.dataset.index)]; field[prop]=event.target.type==="checkbox" ? (event.target.checked ? "1" : "0") : event.target.value; if(prop==="label"&&!field.key) field.key=keyFor(field.label);if(["type","options"].includes(prop)){const key=field.key;render(key);const refreshed=fieldList.querySelector(`[data-key="${CSS.escape(key)}"]`);refreshed.querySelector(".h4bs-field-editor").hidden=false;refreshed.querySelector(".h4bs-edit").setAttribute("aria-expanded","true");refreshed.querySelector(`[data-prop="${prop==="type"?"default":"options"}"]`)?.focus();} sync(); renderPreview(); markDirty(); });
  fieldList.addEventListener("input", (event) => { const card=event.target.closest(".h4bs-field-card"); const prop=event.target.dataset.prop; if(!card||!prop||event.target.type==="checkbox"||event.target.tagName==="SELECT")return; const field=fields[Number(card.dataset.index)]; field[prop]=event.target.value; if(prop==="label"&&!field.key) field.key=keyFor(field.label); sync(); renderPreview(); markDirty(); });
  fieldList.addEventListener("dragstart",(event)=>{const card=event.target.closest(".h4bs-field-card");if(!card)return;dragged=Number(card.dataset.index);card.classList.add("is-dragging");});
  fieldList.addEventListener("dragend",()=>{fieldList.querySelectorAll(".is-dragging").forEach((el)=>el.classList.remove("is-dragging"));dragged=-1;});
  fieldList.addEventListener("dragover",(event)=>event.preventDefault()); fieldList.addEventListener("drop",(event)=>{event.preventDefault();const target=event.target.closest(".h4bs-field-card");if(target&&dragged>=0)move(dragged,Number(target.dataset.index));});
  workspace.querySelector("[data-h4bs-add-field]")?.addEventListener("click",()=>{remember();const field={key:`question_${Date.now()}`,label:"New question",type:"text",required:"0",placeholder:"",options:"",default:"",width:"100"};lastChangedKey=field.key;fields.push(field);render(field.key);markDirty();announce("Question added. Edit its label and answer type.");});
  workspace.querySelector("[data-h4bs-undo]")?.addEventListener("click",()=>{if(!fieldHistory.length)return;fields=fieldHistory.pop();render(lastChangedKey);markDirty();const undo=workspace.querySelector("[data-h4bs-undo]");undo.hidden=fieldHistory.length===0;if(!workspace.contains(document.activeElement)||document.activeElement===document.body)workspace.querySelector("[data-h4bs-add-field]")?.focus();announce("Last field change undone.");});
  workspace.querySelector("[data-h4bs-refresh-preview]")?.addEventListener("click",()=>{renderPreview();announce("Preview refreshed. Nothing was submitted.");});
  const previewTools=document.createElement("div");previewTools.className="h4bs-preview-tools";previewTools.innerHTML='<fieldset><legend>Preview size</legend><button type="button" class="button is-active" data-preview-size="desktop" aria-pressed="true">Desktop</button><button type="button" class="button" data-preview-size="tablet" aria-pressed="false">Tablet</button><button type="button" class="button" data-preview-size="mobile" aria-pressed="false">Mobile</button></fieldset><label>Visitor state <select data-preview-state><option value="form">Filling out the form</option><option value="validation">Required-answer error</option><option value="success">Success message</option><option value="error">Submission error</option></select></label>';
  preview.before(previewTools);
  previewTools.addEventListener("click",(event)=>{const button=event.target.closest("[data-preview-size]");if(!button)return;previewTools.querySelectorAll("[data-preview-size]").forEach((item)=>{const active=item===button;item.classList.toggle("is-active",active);item.setAttribute("aria-pressed",String(active));});preview.dataset.previewSize=button.dataset.previewSize;announce(`${button.textContent.trim()} preview selected.`);});
  previewTools.querySelector("[data-preview-state]").addEventListener("change",(event)=>{const state=event.target.value;renderPreview();if(state!=="form"){const copy=state==="validation"?(form.querySelector('[name="error_message"]')?.value||"Please check required fields."):state==="success"?(form.querySelector('[name="success_message"]')?.value||"Thanks! We received your request."):"We could not send this form. Your answers remain here; please try again.";preview.insertAdjacentHTML("afterbegin",`<div class="notice ${state==="success"?"notice-success":"notice-error"} inline" role="status"><p>${esc(copy)}</p></div>`);}announce("Visitor preview state updated. Nothing was submitted.");});
  const readiness=workspace.querySelector(".h4bs-form-readiness");
  const updateReadiness=()=>{if(!readiness)return;const checked=(name)=>form.querySelector(`[name="${name}"]`)?.checked;const value=(name)=>form.querySelector(`[name="${name}"]`)?.value||"";let host="Off";try{host=value("webhook_url")?new URL(value("webhook_url")).hostname:"Off";}catch(_){host="Invalid address — review before saving";}const captchaMode=value("captcha_mode");const provider=workspace.dataset.h4bsCaptchaProvider||"disabled";const configured=workspace.dataset.h4bsCaptchaConfigured==="1";const effectiveCaptcha=captchaMode==="disabled"?"CAPTCHA disabled for this form":provider!=="turnstile"?"Site CAPTCHA is disabled":configured?"Turnstile active for this form":"Turnstile requested, but site setup is incomplete";readiness.innerHTML=`<h2 id="h4bs-readiness-title">Ready-to-save summary</h2><ul><li><strong>Visitors:</strong> ${value("status")==="active"?"Form is open":"Form is hidden"}</li><li><strong>Staff notice:</strong> ${checked("notify_admin")?esc(value("notify_email")||"Site administrator address"):"Off"}</li><li><strong>Visitor confirmation:</strong> ${checked("send_autoresponder")?"On":"Off"}</li><li><strong>Spam protection:</strong> ${esc(effectiveCaptcha)}; invisible spam trap ${checked("honeypot")?"on":"off"}</li><li><strong>Webhook:</strong> ${esc(host)}</li></ul><p class="description">Preview is always safe: it does not send notices, confirmations, webhooks, stored entries, or CAPTCHA requests.</p>`;};
  rawEditor.addEventListener("input",()=>{try{const parsed=JSON.parse(rawEditor.value);if(!Array.isArray(parsed))throw new Error();fields=parsed;schemaInvalid=false;schema.value=rawEditor.value;workspace.querySelector("[data-h4bs-schema-error]")?.remove();render();markDirty();announce("Raw field data is valid. Review the visual questions before saving.");}catch(_){schemaInvalid=true;saveButton.disabled=true;saveBar.hidden=false;saveState.textContent="Saving blocked — raw field data is invalid";announce("Saving is blocked. Repair the raw field data or restore a known-good copy.");}});
  form.addEventListener("input",()=>{markDirty();updateReadiness();});
  form.addEventListener("submit",async(event)=>{event.preventDefault();if(saveButton.disabled)return;sync();saveButton.disabled=true;saveBar.hidden=false;conflictPanel.hidden=true;saveState.textContent="Saving…";try{const payload=new FormData(form);payload.set("h4bs_visual_ajax","1");const response=await fetch(form.getAttribute("action")||location.href,{method:"POST",body:payload,credentials:"same-origin",headers:{"X-Requested-With":"XMLHttpRequest"}});const result=await response.json();if(!response.ok||!result.success)throw Object.assign(new Error(result?.data?.message||"Save failed. Your changes are still here."),{status:response.status});const data=result.data||{};form.querySelector("[name=id]").value=String(data.id||form.querySelector("[name=id]").value);form.querySelector("[name=revision]").value=String(data.revision||"");form.querySelector("[name=request_id]").value=String(data.next_request_id||crypto.randomUUID());saved=JSON.stringify(fields);metaSaved=metaSnapshot();fieldHistory=[];workspace.querySelector("[data-h4bs-undo]").hidden=true;saveState.textContent="All changes saved";window.history.replaceState(null,"",`${location.pathname}?page=h4bs-forms&view=editor&edit=${data.id}`);announce("Form saved.");}catch(error){saveButton.disabled=false;saveBar.hidden=false;saveState.textContent=error.status===409?"Newer changes exist — your work is retained":"Save failed — your work is retained";if(error.status===409){conflictPanel.hidden=false;conflictPanel.querySelector("[data-h4bs-open-latest]").href=location.href;}announce(error.message);}});
  conflictPanel.querySelector("[data-h4bs-copy-draft]").addEventListener("click",async()=>{sync();const exportData={name:form.querySelector("[name=name]")?.value||"",type:form.querySelector("[name=type]")?.value||"",status:form.querySelector("[name=status]")?.value||"",settings:Object.fromEntries(new FormData(form)),fields};delete exportData.settings.h4bs_form_nonce;try{await navigator.clipboard.writeText(JSON.stringify(exportData,null,2));announce("Your unsaved form data was copied.");}catch(_){const blob=new Blob([JSON.stringify(exportData,null,2)],{type:"application/json"});const link=document.createElement("a");link.href=URL.createObjectURL(blob);link.download="unsaved-form-data.json";link.click();URL.revokeObjectURL(link.href);announce("Your unsaved form data was downloaded.");}});
  window.addEventListener("beforeunload",(event)=>{if(isDirty()){event.preventDefault();event.returnValue="";}});
  new MutationObserver(()=>{const text=saveState.textContent.trim();if(text==="All changes saved")saveBar.hidden=true;else if(text.startsWith("Newer changes"))requestAnimationFrame(()=>{conflictPanel.scrollIntoView({block:"start"});conflictPanel.querySelector("button")?.focus();});else if(text.startsWith("Save failed"))requestAnimationFrame(()=>saveBar.scrollIntoView({block:"nearest"}));}).observe(saveState,{childList:true,subtree:true,characterData:true});
  if (window.matchMedia("(max-width: 782px)").matches && !isNew()) {
    const fieldsPanel = workspace.querySelector('[aria-labelledby="h4bs-fields-title"]');
    const detailsPanel = workspace.querySelector('[aria-labelledby="h4bs-form-basics"]');
    if (fieldsPanel && detailsPanel) form.insertBefore(fieldsPanel, detailsPanel);
  }
  render(); saved=JSON.stringify(fields); metaSaved=metaSnapshot(); markDirty();updateReadiness();
})();

(() => {
  const form = document.querySelector('[data-h4bs-entry-bulk]');
  if (!form) return;
  const boxes = [...document.querySelectorAll('[data-h4bs-entry-select]')];
  const all = document.querySelector('[data-h4bs-entry-select-all]');
  const action = form.querySelector('[data-h4bs-bulk-action]');
  const assignee = form.querySelector('[data-h4bs-bulk-assignee]');
  const submit = form.querySelector('[data-h4bs-bulk-submit]');
  const selected = form.querySelector('[data-h4bs-entry-selected]');
  const consequence = form.querySelector('[data-h4bs-bulk-consequence]');
  const confirmation = form.querySelector('[data-h4bs-bulk-confirmation]');
  const confirmationCopy = confirmation?.querySelector('[data-h4bs-bulk-confirm-copy]');
  const confirmationCancel = confirmation?.querySelector('[data-h4bs-bulk-cancel]');
  const confirmationConfirm = confirmation?.querySelector('[data-h4bs-bulk-confirm]');
  let archiveConfirmed = false;
  const closeConfirmation = (returnFocus = true) => {
    if (!confirmation || confirmation.hidden) return;
    confirmation.hidden = true;
    archiveConfirmed = false;
    if (returnFocus) submit.focus();
  };
  const openConfirmation = (count) => {
    if (!confirmation || !confirmationCopy || !confirmationCancel) return;
    confirmationCopy.textContent = `${count} selected message${count === 1 ? '' : 's'} will move out of Current messages. Stored content and staff notes remain intact, and authorized staff can restore them later.`;
    confirmation.hidden = false;
    confirmationCancel.focus();
  };
  const update = () => {
    const count = boxes.filter((box) => box.checked).length;
    closeConfirmation(false);
    selected.textContent = `${count} selected on this page`;
    submit.disabled = count === 0 || !action.value;
    if (all) {
      all.checked = count > 0 && count === boxes.length;
      all.indeterminate = count > 0 && count < boxes.length;
    }
    const assigning = action.value === 'assign';
    assignee.hidden = !assigning;
    const archive = action.value === 'archive';
    const restore = action.value === 'restore';
    consequence.textContent = archive
      ? `Archive will hide ${count || 'the selected'} messages from Current messages. Their stored content and notes remain intact and can be restored.`
      : restore
        ? `Restore will return ${count || 'the selected'} messages to Current messages.`
        : 'Only the messages selected on this visible page will change. No permanent deletion is available here.';
  };
  all?.addEventListener('change', () => { boxes.forEach((box) => { box.checked = all.checked; }); update(); });
  boxes.forEach((box) => box.addEventListener('change', update));
  action.addEventListener('change', update);
  confirmationCancel?.addEventListener('click', () => closeConfirmation(true));
  confirmationConfirm?.addEventListener('click', () => {
    archiveConfirmed = true;
    confirmation.hidden = true;
    form.requestSubmit(submit);
  });
  confirmation?.addEventListener('keydown', (event) => {
    if (event.key === 'Escape') {
      event.preventDefault();
      closeConfirmation(true);
      return;
    }
    if (event.key !== 'Tab') return;
    const controls = [confirmationCancel, confirmationConfirm].filter((control) => control && !control.disabled);
    if (controls.length === 0) return;
    const first = controls[0];
    const last = controls[controls.length - 1];
    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  });
  form.addEventListener('submit', (event) => {
    const count = boxes.filter((box) => box.checked).length;
    if (count === 0 || !action.value) {
      event.preventDefault();
      selected.textContent = 'Select at least one visible message and choose an action.';
      selected.focus?.();
      return;
    }
    if (action.value === 'archive' && !archiveConfirmed) {
      event.preventDefault();
      openConfirmation(count);
      return;
    }
    archiveConfirmed = false;
    submit.disabled = true;
    selected.textContent = `Applying the action to ${count} selected message${count === 1 ? '' : 's'}…`;
  });
  update();
})();
