/*!
 * BlockWriteAI Signature Plugin
 * Adds an optional digital signature field block.
 */
(function (global) {
  "use strict";

  var BlockWriteAI = global.BlockWriteAI;
  if (!BlockWriteAI || BlockWriteAI.__signaturePluginInstalled) return;
  BlockWriteAI.__signaturePluginInstalled = 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 sanitize = H.sanitizeHTML || function (value) { return String(value || ""); };
  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") + "-" + 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;
    }
  }

  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 signatureWatermarkUrl() {
    var settings = global.BlockWriteAILetterHeadSettings || global.BlockWriteAILetterheadSettings || {};
    var url = settings.watermarkUrlAbsolute ||
      settings.watermark_url_absolute ||
      settings.watermarkUrl ||
      settings.watermark_url ||
      "";
    url = String(url || "").trim();
    if (!url) return logoUrl();
    if (/^(https?:|data:|blob:|file:)/i.test(url)) return url;
    var base = settings.asset_base_url || settings.assetBaseUrl || global.BlockWriteAILetterHeadAssetBase || global.BlockWriteAIPlatformAssetBase || global.BlockWriteAIPlatformBaseUrl || "https://blockwriteai.in/";
    if (url.charAt(0) === "/" || /^uploads\//i.test(url)) return String(base).replace(/\/+$/, "") + "/" + url.replace(/^\/+/, "");
    return url;
  }
  var STORAGE_PREFIX = "blockwriteai-signature:";

  function injectStyles() {
    if (document.querySelector("style[data-blockwriteai-signature-plugin]")) return;
    var style = document.createElement("style");
    style.dataset.blockwriteaiSignaturePlugin = "true";
    style.textContent =
      ".rbe-signature-editor,.rbe-output-signature{position:relative;overflow:hidden;border:1px solid #d7dee8;border-radius:8px;background:#fff;padding:16px;min-height:128px;box-sizing:border-box;max-width:100%;}" +
      ".rbe-signature-editor{display:grid;gap:12px;width:var(--rbe-signature-width,70%);max-width:100%;min-width:min(180px,100%);resize:none;container-type:inline-size;}" +
      ".rbe-signature-watermark{position:absolute;left:50%;top:50%;width:min(300px,76%);max-height:150px;object-fit:contain;opacity:.16;transform:translate(-50%,-50%);pointer-events:none;user-select:none;}" +
      ".rbe-signature-seal{position:absolute;right:14px;top:10px;z-index:4;width:44px;height:44px;background:#d40000;color:#fff;display:none;place-items:center;padding:0;border-radius:4px;box-shadow:0 10px 18px rgba(160,0,0,.22);pointer-events:none;}" +
      ".rbe-output-signature[data-signed='true'] .rbe-signature-seal{display:grid;}" +
      ".rbe-signature-seal-logo{display:block;width:32px;height:32px;}" +
      ".rbe-signature-toolbar{position:relative;z-index:2;display:flex;justify-content:space-between;gap:10px;align-items:center;}" +
      ".rbe-signature-static-label{font:800 14px/1.3 Arial,sans-serif;color:#344054;}" +
      ".rbe-signature-align-tools{display:flex;gap:6px;align-items:center;}" +
      ".rbe-signature-align-btn{width:34px;height:34px;border:1px solid #d7dee8;border-radius:8px;background:#fff;color:#344054;display:inline-grid;place-items:center;cursor:pointer;}" +
      ".rbe-signature-align-btn:hover,.rbe-signature-align-btn.is-active{border-color:#2563eb;background:#eaf1ff;color:#1d4ed8;}" +
      ".rbe-signature-preview{position:relative;z-index:1;display:grid;grid-template-columns:auto 1fr;gap:12px;align-items:center;border:1px dashed #b6c4d6;border-radius:8px;background:rgba(248,251,255,.86);padding:14px;}" +
      ".rbe-signature-preview-name{font-family:'Brush Script MT','Segoe Script','Lucida Handwriting',cursive;font-size:20px;line-height:1.15;color:#111827;white-space:normal;overflow-wrap:anywhere;}" +
      ".rbe-signature-preview-copy{display:grid;gap:4px;color:#344054;font:13px/1.35 Arial,sans-serif;min-width:0;}" +
      ".rbe-signature-preview-copy strong{font-size:15px;color:#172033;}" +
      ".rbe-signature-resize-handle{position:absolute;right:7px;bottom:7px;z-index:3;width:18px;height:18px;border:0;border-radius:5px;background:#2563eb;color:#fff;box-shadow:0 8px 18px rgba(37,99,235,.22);cursor:nwse-resize;display:grid;place-items:center;padding:0;}" +
      ".rbe-signature-resize-handle:before{content:'';width:8px;height:8px;border-right:2px solid currentColor;border-bottom:2px solid currentColor;}" +
      ".rbe-output-signature{display:grid;gap:14px;margin:0 0 15px;container-type:inline-size;overflow:visible;min-width:0;}" +
      ".rbe-output-signature-label{position:relative;z-index:1;font:700 14px/1.4 Arial,sans-serif;color:#344054;}" +
      ".rbe-signature-unsigned{position:relative;z-index:1;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px;align-items:center;width:min(640px,100%);max-width:100%;min-width:0;margin:0 auto;box-sizing:border-box;}" +
      ".rbe-signature-input{width:100%;min-width:0;min-height:42px;border:1px solid #cbd5e1;border-radius:8px;background:#fff;color:#111827;font:15px/1.15 'Brush Script MT','Segoe Script','Lucida Handwriting',cursive;padding:8px 10px;text-align:center;box-sizing:border-box;}" +
      ".rbe-signature-input::placeholder{color:#98a2b3;font:13px/1.35 Arial,sans-serif;}" +
      ".rbe-signature-apply{border:1px solid #1d4ed8;border-radius:8px;background:#2563eb;color:#fff;font:800 14px/1 Arial,sans-serif;padding:13px 16px;cursor:pointer;}" +
      ".rbe-signature-apply:hover{background:#1d4ed8;}" +
      ".rbe-output-signature.has-error .rbe-signature-input{border-color:#dc2626;box-shadow:0 0 0 3px rgba(220,38,38,.12);}" +
      ".rbe-signature-signed{position:relative;z-index:1;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px;align-items:center;min-width:0;min-height:80px;}" +
      ".rbe-signature-signed[hidden],.rbe-signature-unsigned[hidden]{display:none!important;}" +
      ".rbe-signature-name{min-width:0;font-family:'Brush Script MT','Segoe Script','Lucida Handwriting',cursive;font-size:20px;line-height:1.15;color:#050505;overflow-wrap:anywhere;}" +
      ".rbe-signature-meta{min-width:0;font-family:Arial,sans-serif;font-size:15px;line-height:1.18;color:#050505;display:grid;gap:2px;overflow-wrap:anywhere;}" +
      ".rbe-signature-meta strong{font-weight:500;}" +
      ".rbe-signature-meta strong,.rbe-signature-meta span,.rbe-signature-meta time{min-width:0;overflow-wrap:anywhere;}" +
      ".rbe-signature-meta time{font:inherit;}" +
      ".rbe-output-signature.is-compact{padding:10px;gap:10px;}" +
      ".rbe-output-signature.is-compact .rbe-signature-signed,.rbe-output-signature.is-compact .rbe-signature-unsigned{grid-template-columns:1fr;gap:8px;min-height:0;}" +
      ".rbe-output-signature.is-compact .rbe-signature-apply{width:100%;}" +
      ".rbe-output-signature.is-compact .rbe-signature-watermark{width:min(220px,86%);}" +
      ".rbe-output-signature.is-compact .rbe-signature-seal{right:8px;top:8px;width:36px;height:36px;}" +
      ".rbe-output-signature.is-compact .rbe-signature-seal-logo{width:26px;height:26px;}" +
      ".rbe-output-signature.is-compact .rbe-signature-meta{font-size:13px;line-height:1.22;}" +
      "@container (max-width:320px){.rbe-signature-preview,.rbe-signature-signed{grid-template-columns:1fr;gap:8px;min-height:0;}.rbe-signature-unsigned{grid-template-columns:1fr;}.rbe-signature-apply{width:100%;}}" +
      "@media (max-width:720px){.rbe-signature-editor{width:100%!important;}.rbe-signature-toolbar,.rbe-signature-preview,.rbe-signature-unsigned,.rbe-signature-signed{grid-template-columns:1fr;}.rbe-signature-toolbar{align-items:flex-start;}.rbe-signature-preview-name,.rbe-signature-name{white-space:normal;}.rbe-signature-apply{width:100%;}}";
    document.head.appendChild(style);
  }

  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 cleanText(value) {
    return String(value == null ? "" : value).trim();
  }

  function cleanAlignment(value) {
    return value === "left" || value === "right" ? value : "center";
  }

  function cleanWidth(value) {
    value = Number(value || 70);
    if (!Number.isFinite(value)) value = 70;
    return Math.min(100, Math.max(14, Math.round(value)));
  }

  function layoutStyle(width, alignment) {
    width = cleanWidth(width);
    alignment = cleanAlignment(alignment);
    var margin = alignment === "left" ? "margin-left:0;margin-right:auto;" : alignment === "right" ? "margin-left:auto;margin-right:0;" : "margin-left:auto;margin-right:auto;";
    var justify = alignment === "left" ? "justify-self:start;" : alignment === "right" ? "justify-self:end;" : "justify-self:center;";
    return "width:min(100%," + width + "%);" + margin + justify;
  }

  function applySignatureLayout(wrap) {
    if (!wrap) return;
    var width = cleanWidth(wrap.dataset.width);
    var alignment = cleanAlignment(wrap.dataset.alignment);
    wrap.dataset.width = String(width);
    wrap.dataset.alignment = alignment;
    wrap.style.width = "min(100%," + width + "%)";
    wrap.style.marginLeft = alignment === "left" ? "0" : "auto";
    wrap.style.marginRight = alignment === "right" ? "0" : "auto";
    wrap.style.justifySelf = alignment === "left" ? "start" : alignment === "right" ? "end" : "center";
    Array.prototype.slice.call(wrap.querySelectorAll(".rbe-signature-align-btn")).forEach(function (button) {
      var active = button.dataset.align === alignment;
      button.classList.toggle("is-active", active);
      button.setAttribute("aria-pressed", active ? "true" : "false");
    });
  }

  function bindSignatureResize(editor, wrap) {
    var handle = wrap && wrap.querySelector(".rbe-signature-resize-handle");
    if (!handle || wrap.dataset.resizeReady === "true") return;
    wrap.dataset.resizeReady = "true";
    handle.addEventListener("pointerdown", function (event) {
      event.preventDefault();
      event.stopPropagation();
      var parent = wrap.parentElement || wrap;
      var parentWidth = Math.max(1, parent.getBoundingClientRect().width);
      var startX = event.clientX;
      var startWidth = wrap.getBoundingClientRect().width;

      function move(moveEvent) {
        var nextWidth = startWidth + moveEvent.clientX - startX;
        wrap.dataset.width = String(cleanWidth((nextWidth / parentWidth) * 100));
        applySignatureLayout(wrap);
      }

      function up() {
        document.removeEventListener("pointermove", move);
        document.removeEventListener("pointerup", up);
        if (editor && typeof editor.changed === "function") editor.changed(true);
      }

      document.addEventListener("pointermove", move);
      document.addEventListener("pointerup", up);
    });
  }

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

  function readStoredSignature(id) {
    if (!id) return null;
    try {
      return JSON.parse(localStorage.getItem(STORAGE_PREFIX + id) || "null");
    } catch (error) {
      return null;
    }
  }

  function saveStoredSignature(id, record) {
    if (!id) return;
    try {
      localStorage.setItem(STORAGE_PREFIX + id, JSON.stringify(record));
    } catch (error) {
      // Storage is best-effort; the DOM still becomes read-only after signing.
    }
  }

  function assignOutputStorageKeys(root) {
    var boxes = Array.prototype.slice.call((root || document).querySelectorAll(".rbe-output-signature"));
    var counts = {};
    boxes.forEach(function (box) {
      var id = box.dataset.signatureId || "";
      counts[id] = (counts[id] || 0) + 1;
    });
    var seen = {};
    boxes.forEach(function (box) {
      var id = box.dataset.signatureId || uid("signature");
      box.dataset.signatureId = id;
      seen[id] = (seen[id] || 0) + 1;
      box.dataset.signatureStorageKey = counts[id] > 1 ? id + ":" + seen[id] : id;
    });
    return boxes;
  }

  function uniqueEditorSignatureId(block, wrap) {
    var id = (wrap && wrap.dataset.signatureId) || "";
    var root = (block && block.closest && block.closest(".rbe")) || document;
    var signatures = Array.prototype.slice.call(root.querySelectorAll(".rbe-signature-editor"));
    var firstWithId = id ? signatures.find(function (item) { return item.dataset.signatureId === id; }) : null;
    if (!id || (firstWithId && firstWithId !== wrap)) {
      do {
        id = uid("signature");
      } while (signatures.some(function (item) { return item !== wrap && item.dataset.signatureId === id; }));
      if (wrap) wrap.dataset.signatureId = id;
    }
    return id;
  }

  function applySignature(box, record) {
    if (!box || !record || !record.name) return;
    var unsigned = box.querySelector(".rbe-signature-unsigned");
    var signed = box.querySelector(".rbe-signature-signed");
    var name = box.querySelector(".rbe-signature-name");
    var by = box.querySelector(".rbe-signature-by-name");
    var time = box.querySelector(".rbe-signature-date");
    var input = box.querySelector(".rbe-signature-input");
    if (input) {
      input.value = record.name;
      input.readOnly = true;
    }
    if (name) name.textContent = record.name;
    if (by) by.textContent = record.name;
    if (time) {
      time.textContent = record.dateLabel || formatSignatureDate(new Date(record.date || Date.now()));
      if (record.date) time.setAttribute("datetime", record.date);
    }
    if (unsigned) unsigned.hidden = true;
    if (signed) signed.hidden = false;
    box.dataset.signed = "true";
    box.classList.remove("has-error");
    syncSignatureBoxSize(box);
  }

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

  function observeSignatureBox(box) {
    if (!box || box.dataset.signatureResizeObserved === "true") return;
    box.dataset.signatureResizeObserved = "true";
    syncSignatureBoxSize(box);
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", function () {
        syncSignatureBoxSize(box);
      });
      return;
    }
    var observer = new ResizeObserver(function () {
      syncSignatureBoxSize(box);
    });
    observer.observe(box);
  }

  function signOutput(box) {
    var input = box.querySelector(".rbe-signature-input");
    var name = cleanText(input && input.value);
    if (!name) {
      box.classList.add("has-error");
      if (input) input.focus();
      return;
    }
    var now = new Date();
    var record = {
      name: name,
      date: now.toISOString(),
      dateLabel: formatSignatureDate(now)
    };
    saveStoredSignature(box.dataset.signatureStorageKey || box.dataset.signatureId || "", record);
    applySignature(box, record);
    box.dispatchEvent(new CustomEvent("blockwriteai:signature-signed", { bubbles: true, detail: record }));
  }

  function initSignatureOutputs(root) {
    injectStyles();
    assignOutputStorageKeys(root).forEach(function (box) {
      if (box.dataset.signatureReady === "true") return;
      box.dataset.signatureReady = "true";
      observeSignatureBox(box);
      var stored = readStoredSignature(box.dataset.signatureStorageKey || box.dataset.signatureId || "");
      if (stored && stored.name) applySignature(box, stored);
      var input = box.querySelector(".rbe-signature-input");
      var button = box.querySelector(".rbe-signature-apply");
      if (button) {
        button.addEventListener("click", function () {
          signOutput(box);
        });
      }
      if (input) {
        input.addEventListener("input", function () {
          box.classList.remove("has-error");
        });
        input.addEventListener("keydown", function (event) {
          if (event.key === "Enter") {
            event.preventDefault();
            signOutput(box);
          }
        });
      }
    });
  }

  injectStyles();

  BlockWriteAI.registerTool("signature", {
    label: "Signature",
    hint: "Digital signature field",
    icon: "signature",
    premiumFeature: "signature",
    defaultData: function () {
      return {
        signatureId: uid("signature"),
        label: "Signature",
        width: 70,
        alignment: "center"
      };
    },
    render: function (body, data) {
      injectStyles();
      data = data || {};
      var wrap = el("div", "rbe-signature-editor", {
        dataset: {
          signatureId: data.signatureId || uid("signature"),
          width: cleanWidth(data.width),
          alignment: cleanAlignment(data.alignment)
        }
      });
      wrap.appendChild(el("img", "rbe-signature-watermark", { src: signatureWatermarkUrl(), alt: "", "aria-hidden": "true" }));

      var toolbar = el("div", "rbe-signature-toolbar");
      toolbar.appendChild(el("div", "rbe-signature-static-label", { text: "Signature" }));
      var alignTools = el("div", "rbe-signature-align-tools", { role: "toolbar", "aria-label": "Signature alignment" });
      [
        ["left", "align-left", "Align left"],
        ["center", "align-center", "Align center"],
        ["right", "align-right", "Align right"]
      ].forEach(function (item) {
        alignTools.appendChild(
          el("button", "rbe-signature-align-btn", {
            type: "button",
            title: item[2],
            html: svgIcon(item[1], item[2]),
            dataset: { align: item[0] },
            "aria-label": item[2],
            "aria-pressed": cleanAlignment(data.alignment) === item[0] ? "true" : "false",
            disabled: this.readOnly
          })
        );
      }, this);
      toolbar.appendChild(alignTools);
      wrap.appendChild(toolbar);

      var preview = el("div", "rbe-signature-preview");
      preview.appendChild(el("div", "rbe-signature-preview-name", { text: "Casey Jones" }));
      preview.appendChild(
        el("div", "rbe-signature-preview-copy", {
          html:
            "<strong>Blank signature input in preview</strong><span>Users type their name once; the signed block becomes read-only with date and time.</span>"
        })
      );
      wrap.appendChild(preview);
      if (!this.readOnly) {
        wrap.appendChild(el("button", "rbe-signature-resize-handle", { type: "button", title: "Resize signature field", "aria-label": "Resize signature field" }));
      }
      body.appendChild(wrap);
      applySignatureLayout(wrap);
      bindSignatureResize(this, wrap);
      var editor = this;
      Array.prototype.slice.call(wrap.querySelectorAll(".rbe-signature-align-btn")).forEach(function (button) {
        button.addEventListener("click", function () {
          wrap.dataset.alignment = cleanAlignment(button.dataset.align);
          applySignatureLayout(wrap);
          if (editor && typeof editor.changed === "function") editor.changed(true);
        });
      });
    },
    serialize: function (block) {
      var wrap = block.querySelector(".rbe-signature-editor");
      return {
        signatureId: uniqueEditorSignatureId(block, wrap),
        label: "Signature",
        width: cleanWidth(wrap && wrap.dataset.width),
        alignment: cleanAlignment(wrap && wrap.dataset.alignment)
      };
    },
    toHTML: function (data) {
      injectStyles();
      data = data || {};
      var id = data.signatureId || uid("signature");
      var label = "Signature";
      return (
        '<section class="rbe-output-signature" style="' +
        esc(layoutStyle(data.width, data.alignment)) +
        '" data-signature-id="' +
        esc(id) +
        '" data-signed="false">' +
        sealHTML("rbe-signature-seal") +
        '<img class="rbe-signature-watermark" src="' +
        esc(signatureWatermarkUrl()) +
        '" alt="" aria-hidden="true"><div class="rbe-output-signature-label">' +
        esc(label) +
        '</div><div class="rbe-signature-unsigned"><input class="rbe-signature-input" type="text" autocomplete="name" placeholder="' +
        esc("Enter your name here...") +
        '"><button type="button" class="rbe-signature-apply">' +
        svgIcon("file-signature", "Sign") +
        "<span>Sign</span></button></div>" +
        '<div class="rbe-signature-signed" hidden><div class="rbe-signature-name"></div><div class="rbe-signature-meta"><strong>Digitally signed by <span class="rbe-signature-by-name"></span></strong><span>Date: <time class="rbe-signature-date"></time></span></div></div></section>'
      );
    },
    toMarkdown: function (data) {
      return "[Signature field: " + (data && data.label ? data.label : "Signature") + "]";
    }
  });

  global.BlockWriteAISignature = {
    init: initSignatureOutputs,
    sign: signOutput,
    formatDate: formatSignatureDate
  };

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