/*!
 * BlockWriteAI Signature Flow Plugin
 * Adds optional sequential multi-signer signature flows.
 */
(function (global) {
  "use strict";

  var BlockWriteAI = global.BlockWriteAI;
  if (!BlockWriteAI || BlockWriteAI.__signatureFlowPluginInstalled) return;
  BlockWriteAI.__signatureFlowPluginInstalled = true;

  var H = BlockWriteAI.helpers || {};
  var el = H.el;
  var esc = H.escapeHTML || function (value) {
    return String(value == null ? "" : value).replace(/[&<>"]/g, function (ch) {
      return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[ch];
    });
  };
  var svgIcon = H.svgIcon || function (name, label) {
    name = String(name || "circle").trim();
    return '<svg class="rbe-svg-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" data-rbe-icon="' + esc(name) + '"><circle cx="12" cy="12" r="8"/></svg><span class="rbe-sr-only">' + esc(label || name) + "</span>";
  };
  var uid = H.uid || function (prefix) {
    return (prefix || "signature-flow") + "-" + Math.random().toString(36).slice(2, 9);
  };

  function pluginAsset(path) {
    try {
      var base = (document.currentScript && document.currentScript.src) || document.baseURI;
      return new URL(path, base).href;
    } catch (error) {
      return path;
    }
  }

  var STORAGE_PREFIX = "blockwriteai-signature-flow:";

  function isDarkTheme() {
    return !!document.querySelector(".rbe.rbe-theme-dark, .rbe-shell.rbe-theme-dark");
  }

  function logoUrl() {
    if (global.BlockWriteAILogoUrl) return global.BlockWriteAILogoUrl;
    return pluginAsset(isDarkTheme() ? "../blockwriteai-logo-dark.svg" : "../blockwriteai-logo.svg");
  }

  function signatureEventUrl() {
    return global.BlockWriteAISignatureEventUrl ||
      (BlockWriteAI.platformEndpoints && BlockWriteAI.platformEndpoints.signatureEvent) ||
      "https://blockwriteai.in/api/signature_event.php";
  }

  function injectStyles() {
    if (document.querySelector("style[data-blockwriteai-signature-flow-plugin]")) return;
    var style = document.createElement("style");
    style.dataset.blockwriteaiSignatureFlowPlugin = "true";
    style.textContent =
      ".rbe-signature-flow-editor{border:1px solid #d7dee8;border-radius:8px;background:#fff;padding:14px;display:grid;gap:12px;}" +
      ".rbe-signature-flow-top{display:flex;justify-content:space-between;align-items:center;gap:10px;}" +
      ".rbe-signature-flow-top strong{font:800 14px/1.3 Arial,sans-serif;color:#344054;}" +
      ".rbe-signature-flow-steps{display:grid;gap:8px;}" +
      ".rbe-signature-flow-step{display:grid;grid-template-columns:auto minmax(160px,1fr) auto;gap:8px;align-items:center;border:1px solid #e2e8f0;border-radius:8px;background:#fbfdff;padding:8px;}" +
      ".rbe-signature-flow-index{width:28px;height:28px;border-radius:999px;background:#eaf1ff;color:#1d4ed8;display:grid;place-items:center;font:800 12px/1 Arial,sans-serif;}" +
      ".rbe-signature-flow-step input{width:100%;border:1px solid #d7dee8;border-radius:8px;background:#fff;color:#172033;font:14px/1.4 Arial,sans-serif;padding:9px 10px;}" +
      ".rbe-signature-flow-add,.rbe-signature-flow-remove{border:1px solid #d7dee8;border-radius:8px;background:#fff;color:#344054;min-width:34px;height:34px;display:inline-grid;place-items:center;cursor:pointer;}" +
      ".rbe-signature-flow-add:hover{border-color:#16a34a;background:#ecfdf3;color:#07845f;}" +
      ".rbe-signature-flow-remove:hover{border-color:#dc2626;background:#fef2f2;color:#b42318;}" +
      ".rbe-output-signature-flow{display:grid;gap:12px;margin:0 0 15px;}" +
      ".rbe-output-signature-flow-title{font:800 15px/1.35 Arial,sans-serif;color:#172033;}" +
      ".rbe-flow-signature-track{display:flex;flex-wrap:wrap;align-items:stretch;justify-content:center;gap:10px 8px;}" +
      ".rbe-flow-signature-card{position:relative;overflow:visible;container-type:inline-size;border:1px solid #d7dee8;border-radius:8px;background:#fff;padding:10px;display:grid;gap:8px;flex:1 1 170px;min-width:150px;max-width:230px;min-height:126px;box-sizing:border-box;}" +
      ".rbe-flow-signature-card.is-locked{opacity:.68;}" +
      ".rbe-flow-signature-watermark{position:absolute;left:50%;top:52%;width:min(140px,76%);max-height:82px;object-fit:contain;opacity:.14;transform:translate(-50%,-50%);pointer-events:none;user-select:none;}" +
      ".rbe-flow-signature-seal{position:absolute;right:10px;top:8px;z-index:4;width:34px;height:34px;background:#d40000;color:#fff;display:none;place-items:center;padding:0;border-radius:4px;box-shadow:0 8px 14px rgba(160,0,0,.2);pointer-events:none;}" +
      ".rbe-flow-signature-card[data-signed='true'] .rbe-flow-signature-seal{display:grid;}" +
      ".rbe-flow-signature-seal-logo{display:block;width:25px;height:25px;}" +
      ".rbe-flow-signature-head{position:relative;z-index:1;display:grid;gap:6px;font:800 13px/1.3 Arial,sans-serif;color:#344054;}" +
      ".rbe-flow-signature-label{display:block;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}" +
      ".rbe-flow-signature-status{justify-self:start;border-radius:999px;background:#fffbeb;color:#b45309;padding:4px 7px;font-size:10px;line-height:1;font-weight:800;white-space:nowrap;}" +
      ".rbe-flow-signature-card.is-signed{border-color:#86efac;background:#f0fdf4;}" +
      ".rbe-flow-signature-card.is-signed .rbe-flow-signature-status{background:#dcfce7;color:#07845f;}" +
      ".rbe-flow-signature-card.is-locked .rbe-flow-signature-status{background:#fef3c7;color:#92400e;}" +
      ".rbe-flow-signature-connector{align-self:center;display:inline-flex;align-items:center;justify-content:center;flex:0 0 30px;min-height:34px;color:#b45309;font:900 18px/1 Arial,sans-serif;}" +
      ".rbe-flow-signature-connector::before{content:'\\2192';}" +
      ".rbe-flow-signature-connector.is-complete{color:#16a34a;}" +
      ".rbe-flow-signature-connector.is-pending{color:#d97706;}" +
      ".rbe-flow-signature-unsigned{position:relative;z-index:1;display:grid;grid-template-columns:1fr;gap:7px;align-items:center;width:100%;margin:0;}" +
      ".rbe-flow-signature-input{width:100%;min-width:0;min-height:38px;border:1px solid #cbd5e1;border-radius:8px;background:#fff;color:#111827;font:15px/1.2 'Brush Script MT','Segoe Script','Lucida Handwriting',cursive;padding:7px 9px;text-align:center;box-sizing:border-box;}" +
      ".rbe-flow-signature-input::placeholder{color:#98a2b3;font:13px/1.35 Arial,sans-serif;}" +
      ".rbe-flow-signature-apply{border:1px solid #1d4ed8;border-radius:8px;background:#2563eb;color:#fff;font:800 13px/1 Arial,sans-serif;padding:9px 10px;cursor:pointer;}" +
      ".rbe-flow-signature-apply:disabled,.rbe-flow-signature-input:disabled{cursor:not-allowed;opacity:.7;}" +
      ".rbe-flow-signature-card.has-error .rbe-flow-signature-input{border-color:#dc2626;box-shadow:0 0 0 3px rgba(220,38,38,.12);}" +
      ".rbe-flow-signature-signed{position:relative;z-index:1;display:grid;gap:5px;align-items:center;}" +
      ".rbe-flow-signature-signed[hidden],.rbe-flow-signature-unsigned[hidden]{display:none!important;}" +
      ".rbe-flow-signature-name{min-width:0;font-family:'Brush Script MT','Segoe Script','Lucida Handwriting',cursive;font-size:15px;line-height:1.1;color:#050505;overflow-wrap:anywhere;}" +
      ".rbe-flow-signature-meta{min-width:0;font-family:Arial,sans-serif;font-size:12px;line-height:1.2;color:#050505;display:grid;gap:2px;overflow-wrap:anywhere;}" +
      ".rbe-flow-signature-meta strong{font-weight:500;}" +
      ".rbe-flow-signature-meta strong,.rbe-flow-signature-meta span,.rbe-flow-signature-meta time{min-width:0;overflow-wrap:anywhere;}" +
      ".rbe-flow-signature-card.is-compact{padding:8px;gap:6px;}" +
      ".rbe-flow-signature-card.is-compact .rbe-flow-signature-name{font-size:15px;}" +
      ".rbe-flow-signature-card.is-compact .rbe-flow-signature-meta{font-size:11px;line-height:1.22;}" +
      ".rbe-flow-signature-card.is-compact .rbe-flow-signature-seal{right:7px;top:7px;width:30px;height:30px;}" +
      ".rbe-flow-signature-card.is-compact .rbe-flow-signature-seal-logo{width:22px;height:22px;}" +
      "@container (max-width:180px){.rbe-flow-signature-meta{font-size:11px;}.rbe-flow-signature-name{font-size:14px;}}" +
      "@media (max-width:720px){.rbe-signature-flow-step{grid-template-columns:1fr;}.rbe-signature-flow-index{width:100%;border-radius:8px;}.rbe-flow-signature-card{flex-basis:150px;}.rbe-flow-signature-connector{flex-basis:24px;}}";
    document.head.appendChild(style);
  }

  function cleanText(value) {
    return String(value == null ? "" : value).trim();
  }

  function readSessionValue(key) {
    try {
      return sessionStorage.getItem(key) || localStorage.getItem(key) || "";
    } catch (error) {
      return "";
    }
  }

  function runtimeAuthorizationToken() {
    return cleanText(global.BlockWriteAIAuthorizationToken || readSessionValue("bwai_authorization_token"));
  }

  function runtimeLicenseKey() {
    return cleanText(global.BlockWriteAILicenseKey || readSessionValue("blockwriteai_license_key") || readSessionValue("bwai_license_key"));
  }

  function normalizeLookupValue(value) {
    return cleanText(value).toLowerCase().replace(/\s+/g, " ");
  }

  function signatureMatchesLookup(signature, requestedValue) {
    var requested = normalizeLookupValue(requestedValue);
    if (!signature || !requested) return false;
    return normalizeLookupValue(signature.signer_name) === requested || normalizeLookupValue(signature.signer_email) === requested;
  }

  function sealHTML(className) {
    return (
      '<span class="' +
      esc(className) +
      '" aria-hidden="true"><svg class="' +
      esc(className + "-logo") +
      '" viewBox="0 0 32 32" role="img" focusable="false"><path d="M7 4h12l6 6v15a3 3 0 0 1-3 3H10a3 3 0 0 1-3-3z" fill="#fff"/><path d="M19 4v6h6" fill="#ffe5e5"/><path d="M10 23c2-4 3-4 4 0 1-2 2-2 3 0 1-1 2-1 4 0" fill="none" stroke="#d40000" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M22.5 17.5l4.6-4.6 2 2-4.6 4.6-3 .9z" fill="#fff"/><path d="M26.3 13.7l2 2" fill="none" stroke="#d40000" stroke-width="1.1" stroke-linecap="round"/></svg></span>'
    );
  }

  function formatSignatureDate(date) {
    return date.toLocaleString();
  }

  function storageKey(flowId, stepId) {
    return STORAGE_PREFIX + flowId + ":" + stepId;
  }

  function readStored(flowId, stepId) {
    try {
      return JSON.parse(localStorage.getItem(storageKey(flowId, stepId)) || "null");
    } catch (error) {
      return null;
    }
  }

  function saveStored(flowId, stepId, record) {
    try {
      localStorage.setItem(storageKey(flowId, stepId), JSON.stringify(record));
    } catch (error) {
      // Best-effort local preview storage.
    }
  }

  function lookupStoredSignature(card, name) {
    var authorizationToken = runtimeAuthorizationToken();
    var licenseKey = runtimeLicenseKey();
    if ((!authorizationToken && !licenseKey) || !name || typeof fetch !== "function") return Promise.resolve(null);
    var payload = {
      action: "lookup",
      authorization_token: authorizationToken || undefined,
      license_key: authorizationToken ? undefined : licenseKey,
      match_signer_value: name,
      signer_name: name
    };
    var sessionToken = global.BlockWriteAISessionToken || readSessionValue("bwai_session_token") || readSessionValue("blockwriteai_session_token");
    if (sessionToken) payload.session_token = sessionToken;
    return fetch(signatureEventUrl(), {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    })
      .then(function (response) { return response.ok ? response.json() : null; })
      .then(function (data) {
        if (!data || data.ok === false || !data.signature || !signatureMatchesLookup(data.signature, name)) return null;
        return {
          name: data.signature.signer_name || name,
          email: data.signature.signer_email || "",
          role: data.signature.signer_role || "",
          ipAddress: data.signature.ip_address || "",
          signatureHash: data.signature.signature_hash || "",
          date: data.signature.created_at || new Date().toISOString(),
          dateLabel: data.signature.created_at ? formatSignatureDate(new Date(data.signature.created_at)) : formatSignatureDate(new Date())
        };
      })
      .catch(function () { return null; });
  }

  function showSignatureFlowError(card, input) {
    card.classList.add("has-error");
    var status = card.querySelector(".rbe-flow-signature-status");
    if (status) status.textContent = "No verified signature found.";
    if (input) input.focus();
  }

  function flowHasSignatureHash(flow, card, signatureHash) {
    signatureHash = cleanText(signatureHash).toLowerCase();
    if (!flow || !signatureHash) return false;
    return Array.prototype.slice.call(flow.querySelectorAll(".rbe-flow-signature-card")).some(function (item) {
      return item !== card && item.dataset.signed === "true" && cleanText(item.dataset.signatureHash).toLowerCase() === signatureHash;
    });
  }

  function showSignatureFlowDuplicateError(card, input) {
    card.classList.add("has-error");
    var status = card.querySelector(".rbe-flow-signature-status");
    if (status) status.textContent = "Signature already used in this flow.";
    if (input) input.focus();
  }

  function normalizeSteps(steps) {
    var list = Array.isArray(steps) ? steps : [];
    if (!list.length) {
      list = [
        { id: uid("signer"), label: "Signer 1" },
        { id: uid("signer"), label: "Signer 2" },
        { id: uid("signer"), label: "Signer 3" }
      ];
    }
    return list.map(function (step, index) {
      step = step || {};
      return {
        id: step.id || uid("signer"),
        label: cleanText(step.label) || "Signer " + (index + 1)
      };
    });
  }

  function createEditorStep(editor, step, index) {
    var row = el("div", "rbe-signature-flow-step", { dataset: { stepId: step.id || uid("signer") } });
    row.appendChild(el("span", "rbe-signature-flow-index", { text: index + 1 }));
    row.appendChild(
      el("input", "rbe-signature-flow-label", {
        type: "text",
        value: step.label || "Signer " + (index + 1),
        placeholder: "Signer name or role",
        disabled: editor.readOnly
      })
    );
    row.appendChild(
      el("button", "rbe-signature-flow-remove", {
        type: "button",
        title: "Remove signer",
        "aria-label": "Remove signer",
        html: svgIcon("trash-can", "Remove signer"),
        disabled: editor.readOnly
      })
    );
    return row;
  }

  function refreshEditorStepNumbers(wrap) {
    Array.prototype.slice.call(wrap.querySelectorAll(".rbe-signature-flow-step")).forEach(function (row, index) {
      var badge = row.querySelector(".rbe-signature-flow-index");
      if (badge) badge.textContent = index + 1;
      var input = row.querySelector(".rbe-signature-flow-label");
      if (input && !cleanText(input.value)) input.placeholder = "Signer " + (index + 1);
    });
  }

  function createFlowConnector() {
    var connector = document.createElement("span");
    connector.className = "rbe-flow-signature-connector is-pending";
    connector.setAttribute("aria-hidden", "true");
    return connector;
  }

  function refreshFlowConnectors(track) {
    if (!track) return [];
    Array.prototype.slice.call(track.querySelectorAll(".rbe-flow-signature-connector")).forEach(function (connector) {
      connector.remove();
    });
    var cards = Array.prototype.slice.call(track.children).filter(function (child) {
      return child.classList && child.classList.contains("rbe-flow-signature-card");
    });
    cards.forEach(function (card, index) {
      if (index < cards.length - 1) {
        track.insertBefore(createFlowConnector(), card.nextSibling);
      }
    });
    return cards;
  }

  function ensureFlowTrack(flow) {
    var track = null;
    Array.prototype.slice.call(flow.children).some(function (child) {
      if (child.classList && child.classList.contains("rbe-flow-signature-track")) {
        track = child;
        return true;
      }
      return false;
    });
    if (!track) {
      track = document.createElement("div");
      track.className = "rbe-flow-signature-track";
      var title = flow.querySelector(".rbe-output-signature-flow-title");
      if (title && title.parentNode === flow) {
        flow.insertBefore(track, title.nextSibling);
      } else {
        flow.appendChild(track);
      }
    }
    Array.prototype.slice.call(flow.children).forEach(function (child) {
      if (child !== track && child.classList && child.classList.contains("rbe-flow-signature-card")) {
        track.appendChild(child);
      }
    });
    refreshFlowConnectors(track);
    return track;
  }

  function applySignedStep(card, record) {
    if (!card || !record || !record.name) return;
    card.classList.add("is-signed");
    card.classList.remove("is-locked", "has-error");
    card.dataset.signed = "true";
    var unsigned = card.querySelector(".rbe-flow-signature-unsigned");
    var signed = card.querySelector(".rbe-flow-signature-signed");
    var status = card.querySelector(".rbe-flow-signature-status");
    var name = card.querySelector(".rbe-flow-signature-name");
    var by = card.querySelector(".rbe-flow-signature-by-name");
    var email = card.querySelector(".rbe-flow-signature-email");
    var ip = card.querySelector(".rbe-flow-signature-ip");
    var time = card.querySelector(".rbe-flow-signature-date");
    var input = card.querySelector(".rbe-flow-signature-input");
    if (input) {
      input.value = record.name;
      input.readOnly = true;
    }
    if (unsigned) unsigned.hidden = true;
    if (signed) signed.hidden = false;
    if (status) status.textContent = "Signed";
    if (name) name.textContent = record.name;
    if (by) by.textContent = record.name;
    if (email) email.textContent = record.email || "";
    if (ip) ip.textContent = record.ipAddress || "";
    if (time) {
      time.textContent = record.dateLabel || formatSignatureDate(new Date(record.date || Date.now()));
      if (record.date) time.setAttribute("datetime", record.date);
    }
    card.dataset.signatureHash = record.signatureHash || "";
    syncFlowCardSize(card);
  }

  function syncFlowCardSize(card) {
    if (!card || !card.getBoundingClientRect) return;
    var width = card.getBoundingClientRect().width;
    card.classList.toggle("is-compact", width > 0 && width < 190);
  }

  function observeFlowCard(card) {
    if (!card || card.dataset.flowCardResizeObserved === "true") return;
    card.dataset.flowCardResizeObserved = "true";
    syncFlowCardSize(card);
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", function () {
        syncFlowCardSize(card);
      });
      return;
    }
    var observer = new ResizeObserver(function () {
      syncFlowCardSize(card);
    });
    observer.observe(card);
  }

  function updateFlowLocks(flow) {
    var track = ensureFlowTrack(flow);
    var cards = Array.prototype.slice.call(track.querySelectorAll(".rbe-flow-signature-card"));
    var connectors = Array.prototype.slice.call(track.querySelectorAll(".rbe-flow-signature-connector"));
    var allSigned = cards.length > 0;
    var previousSigned = true;
    cards.forEach(function (card, index) {
      var isSigned = card.dataset.signed === "true";
      if (!isSigned) allSigned = false;
      var unlocked = previousSigned || isSigned;
      card.classList.toggle("is-locked", !unlocked);
      card.classList.toggle("is-active", unlocked && !isSigned);
      card.classList.toggle("is-pending", !isSigned);
      var input = card.querySelector(".rbe-flow-signature-input");
      var button = card.querySelector(".rbe-flow-signature-apply");
      var status = card.querySelector(".rbe-flow-signature-status");
      if (!isSigned) {
        if (input) input.disabled = !unlocked;
        if (button) button.disabled = !unlocked;
        if (status) status.textContent = unlocked ? "Ready to sign" : "Pending";
      }
      if (connectors[index]) {
        connectors[index].classList.toggle("is-complete", isSigned);
        connectors[index].classList.toggle("is-pending", !isSigned);
      }
      previousSigned = isSigned;
    });
    flow.dataset.complete = allSigned ? "true" : "false";
  }

  function signFlowStep(card) {
    if (!card || card.classList.contains("is-locked")) return;
    var input = card.querySelector(".rbe-flow-signature-input");
    var name = cleanText(input && input.value);
    if (!name) {
      card.classList.add("has-error");
      if (input) input.focus();
      return;
    }
    var flow = card.closest(".rbe-output-signature-flow");
    lookupStoredSignature(card, name).then(function (matchedRecord) {
      if (!matchedRecord) {
        showSignatureFlowError(card, input);
        return;
      }
      var record = matchedRecord;
      if (flowHasSignatureHash(flow, card, record.signatureHash)) {
        showSignatureFlowDuplicateError(card, input);
        return;
      }
      saveStored(flow.dataset.flowId || "", card.dataset.stepId || "", record);
      applySignedStep(card, record);
      updateFlowLocks(flow);
      card.dispatchEvent(new CustomEvent("blockwriteai:signature-flow-signed", { bubbles: true, detail: record }));
    });
  }

  function initFlowOutputs(root) {
    injectStyles();
    Array.prototype.slice.call((root || document).querySelectorAll(".rbe-output-signature-flow")).forEach(function (flow) {
      if (flow.dataset.flowReady === "true") return;
      flow.dataset.flowReady = "true";
      var flowId = flow.dataset.flowId || uid("signature-flow");
      flow.dataset.flowId = flowId;
      ensureFlowTrack(flow);
      Array.prototype.slice.call(flow.querySelectorAll(".rbe-flow-signature-card")).forEach(function (card) {
        observeFlowCard(card);
        var stepId = card.dataset.stepId || uid("signer");
        card.dataset.stepId = stepId;
        var stored = readStored(flowId, stepId);
        if (stored && stored.name && stored.signatureHash) applySignedStep(card, stored);
        var input = card.querySelector(".rbe-flow-signature-input");
        var button = card.querySelector(".rbe-flow-signature-apply");
        if (button) {
          button.addEventListener("click", function () {
            signFlowStep(card);
          });
        }
        if (input) {
          input.addEventListener("input", function () {
            card.classList.remove("has-error");
          });
          input.addEventListener("keydown", function (event) {
            if (event.key === "Enter") {
              event.preventDefault();
              signFlowStep(card);
            }
          });
        }
      });
      updateFlowLocks(flow);
    });
  }

  injectStyles();

  BlockWriteAI.registerTool("signatureFlow", {
    label: "Signature Flow",
    hint: "Sequential signer approvals",
    icon: "people-arrows",
    premiumFeature: "signature_flow",
    defaultData: function () {
      return {
        flowId: uid("signature-flow"),
        title: "Signature Flow",
        steps: normalizeSteps()
      };
    },
    render: function (body, data) {
      injectStyles();
      data = data || {};
      var wrap = el("div", "rbe-signature-flow-editor", { dataset: { flowId: data.flowId || uid("signature-flow") } });
      var top = el("div", "rbe-signature-flow-top");
      top.appendChild(el("strong", "", { text: "Signature Flow" }));
      top.appendChild(
        el("button", "rbe-signature-flow-add", {
          type: "button",
          title: "Add signer",
          "aria-label": "Add signer",
          html: svgIcon("circle-plus", "Add signer"),
          disabled: this.readOnly
        })
      );
      wrap.appendChild(top);
      var stepsWrap = el("div", "rbe-signature-flow-steps");
      normalizeSteps(data.steps).forEach(function (step, index) {
        stepsWrap.appendChild(createEditorStep(this, step, index));
      }, this);
      wrap.appendChild(stepsWrap);
      body.appendChild(wrap);

      var editor = this;
      var addButton = wrap.querySelector(".rbe-signature-flow-add");
      if (addButton) {
        addButton.addEventListener("click", function () {
          var index = stepsWrap.querySelectorAll(".rbe-signature-flow-step").length;
          stepsWrap.appendChild(createEditorStep(editor, { id: uid("signer"), label: "Signer " + (index + 1) }, index));
          refreshEditorStepNumbers(wrap);
          if (editor && typeof editor.changed === "function") editor.changed(true);
        });
      }
      stepsWrap.addEventListener("click", function (event) {
        var remove = event.target.closest(".rbe-signature-flow-remove");
        if (!remove || editor.readOnly) return;
        var rows = stepsWrap.querySelectorAll(".rbe-signature-flow-step");
        if (rows.length <= 1) return;
        remove.closest(".rbe-signature-flow-step").remove();
        refreshEditorStepNumbers(wrap);
        if (editor && typeof editor.changed === "function") editor.changed(true);
      });
    },
    serialize: function (block) {
      var wrap = block.querySelector(".rbe-signature-flow-editor");
      return {
        flowId: (wrap && wrap.dataset.flowId) || uid("signature-flow"),
        title: "Signature Flow",
        steps: Array.prototype.slice.call(block.querySelectorAll(".rbe-signature-flow-step")).map(function (row, index) {
          return {
            id: row.dataset.stepId || uid("signer"),
            label: cleanText((row.querySelector(".rbe-signature-flow-label") || {}).value) || "Signer " + (index + 1)
          };
        })
      };
    },
    toHTML: function (data) {
      injectStyles();
      data = data || {};
      var flowId = data.flowId || uid("signature-flow");
      var steps = normalizeSteps(data.steps);
      return (
        '<section class="rbe-output-signature-flow" data-flow-id="' +
        esc(flowId) +
        '"><div class="rbe-output-signature-flow-title">Signature Flow</div><div class="rbe-flow-signature-track">' +
        steps.map(function (step, index) {
          return (
            '<section class="rbe-flow-signature-card" data-step-id="' +
            esc(step.id) +
            '" data-signed="false">' +
            sealHTML("rbe-flow-signature-seal") +
            '<img class="rbe-flow-signature-watermark" src="' +
            esc(logoUrl()) +
            '" alt="" aria-hidden="true"><div class="rbe-flow-signature-head"><span class="rbe-flow-signature-label">' +
            esc(index + 1 + ". " + step.label) +
            '</span><span class="rbe-flow-signature-status">Waiting</span></div><div class="rbe-flow-signature-unsigned"><input class="rbe-flow-signature-input" type="text" autocomplete="name" placeholder="Enter signer name or email..."><button type="button" class="rbe-flow-signature-apply">' +
            svgIcon("file-signature", "Sign") +
            '<span>Sign</span></button></div><div class="rbe-flow-signature-signed" hidden><div class="rbe-flow-signature-name"></div><div class="rbe-flow-signature-meta"><strong>Signer Name: <span class="rbe-flow-signature-by-name"></span></strong><span>Signer Email: <span class="rbe-flow-signature-email"></span></span><span>IP Address: <span class="rbe-flow-signature-ip"></span></span><span>Date &amp; Time: <time class="rbe-flow-signature-date"></time></span></div></div></section>' +
            (index < steps.length - 1 ? '<span class="rbe-flow-signature-connector is-pending" aria-hidden="true"></span>' : "")
          );
        }).join("") +
        "</div></section>"
      );
    },
    toMarkdown: function (data) {
      return "Signature Flow\n" + normalizeSteps(data && data.steps).map(function (step, index) {
        return index + 1 + ". " + step.label;
      }).join("\n");
    }
  });

  global.BlockWriteAISignatureFlow = {
    init: initFlowOutputs,
    sign: signFlowStep,
    update: updateFlowLocks
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", function () {
      initFlowOutputs(document);
    });
  } else {
    setTimeout(function () {
      initFlowOutputs(document);
    }, 0);
  }
})(typeof window !== "undefined" ? window : this);
