/*!
 * BlockWriteAI Drawing Plugin
 * Adds the licensed freehand drawing block.
 */
(function (global) {
  "use strict";

  var BlockWriteAI = global.BlockWriteAI;
  if (!BlockWriteAI || BlockWriteAI.__drawingPluginInstalled) return;
  BlockWriteAI.__drawingPluginInstalled = 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>";
  };

  function injectStyles() {
    if (document.querySelector("style[data-blockwriteai-drawing]")) return;
    var style = document.createElement("style");
    style.dataset.blockwriteaiDrawing = "true";
    style.textContent =
      ".rbe-drawing-block{border:1px solid var(--rbe-border,#d7dee8);border-radius:8px;background:#fff;padding:12px;display:grid;gap:12px;}" +
      ".rbe-drawing-block .rbe-plugin-toolbar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;}" +
      ".rbe-drawing-block .rbe-plugin-toolbar label{display:inline-flex;align-items:center;gap:7px;font-size:12px;font-weight:750;color:#667085;}" +
      ".rbe-drawing-block .rbe-plugin-toolbar input{border:1px solid var(--rbe-border,#d7dee8);border-radius:7px;background:#fff;color:#172033;font:14px/1.4 Arial,sans-serif;padding:8px 9px;}" +
      ".rbe-drawing-block .rbe-plugin-toolbar input[type='color']{width:40px;min-width:40px;height:34px;padding:3px;}" +
      ".rbe-drawing-text-input{min-width:220px;flex:1 1 260px;}" +
      ".rbe-drawing-text-apply{min-width:38px;}" +
      ".rbe-drawing-shell{display:grid;gap:10px;}" +
      ".rbe-drawing-canvas{width:100%;height:260px;border:1px solid #cbd5e1;border-radius:8px;background:#fff;touch-action:none;}" +
      ".rbe-output-drawing{margin:0 0 15px;}" +
      ".rbe-output-drawing img{max-width:100%;border:1px solid #d7dee8;border-radius:8px;background:#fff;}" +
      "@media (max-width:640px){.rbe-drawing-block{padding:10px;gap:10px;}.rbe-drawing-block .rbe-plugin-toolbar{display:grid;grid-template-columns:1fr;align-items:stretch;}.rbe-drawing-block .rbe-plugin-toolbar label{width:100%;justify-content:space-between;}.rbe-drawing-block .rbe-plugin-toolbar input{width:100%;}.rbe-drawing-canvas{height:220px;}}";
    document.head.appendChild(style);
  }

  function drawingTextSvgDataUri(text, color) {
    var safeColor = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(color || "") ? color : "#2f1830";
    var words = String(text || "Signature text").trim().split(/\s+/);
    var lineOne = words.slice(0, Math.ceil(words.length / 2)).join(" ");
    var lineTwo = words.slice(Math.ceil(words.length / 2)).join(" ");
    var hasTwoLines = !!lineTwo;
    var svg = [
      '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="320" viewBox="0 0 900 320">',
      '<rect width="900" height="320" rx="16" fill="#ffffff"/>',
      '<text x="450" y="' + (hasTwoLines ? "138" : "176") + '" text-anchor="middle" font-family="Mabriella, \'Brush Script MT\', \'Segoe Script\', \'Lucida Handwriting\', cursive" font-size="' + (hasTwoLines ? "104" : "118") + '" font-weight="400" fill="' + esc(safeColor) + '">' + esc(lineOne) + "</text>",
      hasTwoLines ? '<text x="450" y="244" text-anchor="middle" font-family="Mabriella, \'Brush Script MT\', \'Segoe Script\', \'Lucida Handwriting\', cursive" font-size="104" font-weight="400" fill="' + esc(safeColor) + '">' + esc(lineTwo) + "</text>" : "",
      "</svg>"
    ].join("");
    return "data:image/svg+xml;charset=UTF-8," + encodeURIComponent(svg);
  }

  BlockWriteAI.registerTool("drawing", {
    label: "Drawing",
    hint: "Freehand sketch canvas",
    icon: "pen-nib",
    premiumFeature: "drawing",
    defaultData: { image: "", color: "#172033", size: 4, text: "" },
    render: function (body, data) {
      injectStyles();
      var editor = this;
      data = data || {};
      var wrap = el("div", "rbe-drawing-block");
      wrap.dataset.initialImage = data.image || data.url || data.src || "";
      if (!wrap.dataset.initialImage && data.text) {
        wrap.dataset.initialImage = drawingTextSvgDataUri(data.text, data.color || "#2f1830");
      }
      wrap.dataset.drawingDirty = "false";
      wrap.innerHTML =
        '<div class="rbe-plugin-toolbar">' +
        '<label>Pen <input class="rbe-drawing-color" type="color"></label>' +
        '<label>Size <input class="rbe-drawing-size" type="range" min="1" max="24"></label>' +
        '<input class="rbe-drawing-text-input" type="text" placeholder="Type name or text">' +
        '<button type="button" class="rbe-small-btn rbe-drawing-text-apply" title="Convert text to Mabriella style" aria-label="Convert text to Mabriella style">' + svgIcon("wand-magic-sparkles", "Convert text") + "</button>" +
        '<button type="button" class="rbe-small-btn rbe-drawing-clear">' + svgIcon("eraser", "Clear drawing") + "</button>" +
        '</div><div class="rbe-drawing-shell"><canvas class="rbe-drawing-canvas" width="900" height="320"></canvas></div>';
      body.appendChild(wrap);

      var canvas = wrap.querySelector("canvas");
      var ctx = canvas.getContext("2d");
      wrap.querySelector(".rbe-drawing-color").value = data.color || "#172033";
      wrap.querySelector(".rbe-drawing-size").value = data.size || 4;
      wrap.querySelector(".rbe-drawing-text-input").value = data.text || "";

      function loadImage(source) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        if (!source) return;
        var image = new Image();
        image.onload = function () { ctx.drawImage(image, 0, 0, canvas.width, canvas.height); };
        image.src = source;
      }

      if (wrap.dataset.initialImage) loadImage(wrap.dataset.initialImage);

      var drawing = false;
      function point(event) {
        var rect = canvas.getBoundingClientRect();
        return { x: ((event.clientX - rect.left) / rect.width) * canvas.width, y: ((event.clientY - rect.top) / rect.height) * canvas.height };
      }

      canvas.addEventListener("pointerdown", function (event) {
        drawing = true;
        wrap.dataset.drawingDirty = "true";
        canvas.setPointerCapture(event.pointerId);
        var p = point(event);
        ctx.beginPath();
        ctx.moveTo(p.x, p.y);
      });
      canvas.addEventListener("pointermove", function (event) {
        if (!drawing) return;
        var p = point(event);
        ctx.strokeStyle = wrap.querySelector(".rbe-drawing-color").value;
        ctx.lineWidth = Number(wrap.querySelector(".rbe-drawing-size").value || 4);
        ctx.lineCap = "round";
        ctx.lineJoin = "round";
        ctx.lineTo(p.x, p.y);
        ctx.stroke();
      });
      canvas.addEventListener("pointerup", function () {
        drawing = false;
        editor.changed(true);
      });
      wrap.querySelector(".rbe-drawing-text-apply").addEventListener("click", function () {
        var input = wrap.querySelector(".rbe-drawing-text-input");
        var text = (input.value || "").trim();
        if (!text) {
          input.focus();
          return;
        }
        wrap.dataset.initialImage = drawingTextSvgDataUri(text, wrap.querySelector(".rbe-drawing-color").value || "#2f1830");
        wrap.dataset.drawingDirty = "false";
        loadImage(wrap.dataset.initialImage);
        editor.changed(true);
      });
      wrap.querySelector(".rbe-drawing-clear").addEventListener("click", function () {
        wrap.dataset.initialImage = "";
        wrap.dataset.drawingDirty = "true";
        wrap.querySelector(".rbe-drawing-text-input").value = "";
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        editor.changed(true);
      });
    },
    serialize: function (block) {
      var canvas = block.querySelector(".rbe-drawing-canvas");
      var drawingBlock = block.querySelector(".rbe-drawing-block") || block;
      var initialImage = drawingBlock.dataset.initialImage || "";
      var payload = {
        image: "",
        color: (block.querySelector(".rbe-drawing-color") || {}).value || "#172033",
        size: Number((block.querySelector(".rbe-drawing-size") || {}).value || 4),
        text: (block.querySelector(".rbe-drawing-text-input") || {}).value || ""
      };
      if (initialImage && drawingBlock.dataset.drawingDirty !== "true") {
        payload.image = initialImage;
        return payload;
      }
      payload.image = canvas ? canvas.toDataURL("image/png") : "";
      return payload;
    },
    toHTML: function (data) {
      data = data || {};
      var image = data.image || data.url || data.src || (data.diagram && data.diagram.image) || "";
      if (!image && data.text) image = drawingTextSvgDataUri(data.text, data.color || "#2f1830");
      return image ? '<figure class="rbe-output-drawing"><img src="' + esc(image) + '" alt="Drawing"></figure>' : "";
    },
    toMarkdown: function () {
      return "![Drawing](drawing.png)";
    }
  });

  injectStyles();
})(typeof window !== "undefined" ? window : this);
