/*!
 * BlockWriteAI Letterhead Plugin
 * License-gated A4 letterhead block with nested content.
 */
(function (global) {
  "use strict";

  var BlockWriteAI = global.BlockWriteAI;
  if (!BlockWriteAI || BlockWriteAI.__letterHeadInstalled) return;
  BlockWriteAI.__letterHeadInstalled = 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 inline = H.renderOutputInline || sanitize;
  var uid = H.uid || function (prefix) { return (prefix || "block") + "-" + Math.random().toString(36).slice(2, 9); };
  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 CHILD_TYPES = [
    ["paragraph", "Text"],
    ["heading", "Heading"],
    ["list", "List"],
    ["checklist", "Checklist"],
    ["quote", "Quote"],
    ["table", "Table"],
    ["callout", "Callout"],
    ["delimiter", "Divider"],
    ["image", "Image"],
    ["signature", "Signature"]
  ];

  function injectStyles() {
    if (document.querySelector("style[data-blockwriteai-letterhead]")) return;
    var style = document.createElement("style");
    style.dataset.blockwriteaiLetterhead = "true";
    style.textContent =
      ".rbe-letterhead-editor{display:grid;gap:12px;border:1px solid var(--rbe-border,#d7dee8);border-radius:8px;background:var(--rbe-surface-soft,#f8fbff);color:var(--rbe-text,#172033);padding:12px;}" +
      ".rbe-letterhead-locked-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;align-items:stretch;}" +
      ".rbe-letterhead-locked-details>div{display:grid;gap:5px;border:1px solid var(--rbe-border,#d7dee8);border-radius:7px;background:var(--rbe-surface,#fff);color:var(--rbe-text,#172033);padding:8px 9px;min-width:0;}" +
      ".rbe-letterhead-locked-details span{font-size:12px;font-weight:800;color:var(--rbe-muted,#667085);}" +
      ".rbe-letterhead-locked-details strong{font:600 14px/1.35 Arial,sans-serif;color:var(--rbe-text,#172033);overflow-wrap:anywhere;}" +
      ".rbe-letterhead-locked-wide{grid-column:1/-1;}" +
      ".rbe-letterhead-nested-canvas{display:grid;gap:10px;border:1px dashed var(--rbe-border,#cbd5e1);border-radius:8px;background:var(--rbe-surface,#fff);color:var(--rbe-text,#172033);padding:10px;}" +
      ".rbe-letterhead-nested-canvas>.rbe-block{margin:0;}" +
      ".rbe.rbe-theme-dark .rbe-letterhead-editor{border-color:var(--rbe-border,#334155);background:var(--rbe-surface-soft,#1f2937);color:var(--rbe-text,#e5e7eb);}" +
      ".rbe.rbe-theme-dark .rbe-letterhead-locked-details>div,.rbe.rbe-theme-dark .rbe-letterhead-nested-canvas{border-color:var(--rbe-border,#334155);background:var(--rbe-surface,#111827);color:var(--rbe-text,#e5e7eb);}" +
      ".rbe.rbe-theme-dark .rbe-letterhead-locked-details span{color:var(--rbe-muted,#aab8cf);}" +
      ".rbe.rbe-theme-dark .rbe-letterhead-locked-details strong,.rbe.rbe-theme-dark .rbe-letterhead-nested-canvas .rbe-editable,.rbe.rbe-theme-dark .rbe-letterhead-nested-canvas .rbe-heading,.rbe.rbe-theme-dark .rbe-letterhead-nested-canvas .rbe-list-marker,.rbe.rbe-theme-dark .rbe-letterhead-nested-canvas .rbe-check-text{color:var(--rbe-text,#e5e7eb)!important;}" +
      ".rbe.rbe-theme-dark .rbe-letterhead-nested-canvas .rbe-editable *{color:inherit!important;}" +
      ".rbe.rbe-theme-dark .rbe-letterhead-nested-canvas .rbe-heading-level,.rbe.rbe-theme-dark .rbe-letterhead-nested-canvas select{border-color:var(--rbe-border,#334155);background:var(--rbe-surface,#111827);color:var(--rbe-text,#e5e7eb);}" +
      ".rbe-letterhead-sheet,.rbe-output-letterhead-sheet{position:relative;display:flex;flex-direction:column;width:min(100%,794px);min-height:1123px;margin:0 auto 18px;padding:54px 60px;border:1px solid #d7dee8;background:#fff;color:#172033;box-shadow:0 16px 42px rgba(15,23,42,.08);overflow:hidden;break-after:page;page-break-after:always;}" +
      ".rbe-letterhead-watermark,.rbe-output-letterhead-watermark{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;opacity:.08;z-index:0;}" +
      ".rbe-letterhead-watermark img,.rbe-output-letterhead-watermark img{max-width:58%;max-height:58%;object-fit:contain;}" +
      ".rbe-letterhead-head,.rbe-output-letterhead-head{position:relative;z-index:1;display:table;width:100%;table-layout:fixed;border-collapse:collapse;}" +
      ".rbe-letterhead-company,.rbe-output-letterhead-company{display:grid;gap:4px;min-width:0;}" +
      ".rbe-output-letterhead-company{display:table-cell;vertical-align:top;padding-right:20px;}" +
      ".rbe-output-letterhead-logo-cell{display:table-cell;width:108px;vertical-align:top;text-align:right;}" +
      ".rbe-letterhead-company strong,.rbe-output-letterhead-company strong{display:block;margin:0 0 4px;font-size:22px;line-height:1.15;color:#101828;}" +
      ".rbe-letterhead-company span,.rbe-output-letterhead-company span{display:block;font-size:12px;line-height:1.45;color:#475467;overflow-wrap:anywhere;}" +
      ".rbe-letterhead-logo,.rbe-output-letterhead-logo{justify-self:end;width:96px;height:72px;object-fit:contain;}" +
      ".rbe-letterhead-rule,.rbe-output-letterhead-rule{position:relative;z-index:1;border:0;border-top:1px solid #cbd5e1;width:100%;margin:16px 0;}" +
      ".rbe-letterhead-body,.rbe-output-letterhead-body{position:relative;z-index:1;flex:1;display:block;min-height:760px;}" +
      ".rbe-letterhead-body>*{break-inside:avoid;page-break-inside:avoid;}" +
      ".rbe-letterhead-foot,.rbe-output-letterhead-foot{position:relative;z-index:1;display:table;width:100%;table-layout:fixed;border-collapse:collapse;font-size:12px;color:#475467;}" +
      ".rbe-output-letterhead-foot>span{display:table-cell;vertical-align:middle;width:33.333%;}" +
      ".rbe-letterhead-foot-center,.rbe-output-letterhead-foot-center{text-align:center;font-weight:800;color:#172033;}" +
      ".rbe-letterhead-foot-right,.rbe-output-letterhead-foot-right{text-align:right;}" +
      "@media(max-width:780px){.rbe-letterhead-locked-details{grid-template-columns:1fr;}.rbe-letterhead-sheet,.rbe-output-letterhead-sheet{min-height:0;padding:30px 20px;}.rbe-letterhead-head,.rbe-output-letterhead-head{grid-template-columns:1fr;}.rbe-letterhead-logo,.rbe-output-letterhead-logo{justify-self:start;}.rbe-letterhead-body,.rbe-output-letterhead-body{min-height:420px;}.rbe-letterhead-foot,.rbe-output-letterhead-foot{grid-template-columns:1fr;}.rbe-letterhead-foot-center,.rbe-letterhead-foot-right,.rbe-output-letterhead-foot-center,.rbe-output-letterhead-foot-right{text-align:left;}}" +
      "@media print{@page{size:A4;margin:0}.rbe-output-letterhead-sheet{width:210mm;min-height:297mm;margin:0;border:0;box-shadow:none;break-after:page;page-break-after:always;}.rbe-output-letterhead-sheet:last-child{break-after:auto;page-break-after:auto;}}";
    document.head.appendChild(style);
  }

  function value(data, key, fallback) {
    return String(data && data[key] != null ? data[key] : fallback || "");
  }

  function valueAny(data, camelKey, snakeKey, fallback) {
    if (data && data[camelKey] != null) return String(data[camelKey]);
    if (snakeKey && data && data[snakeKey] != null) return String(data[snakeKey]);
    return String(fallback || "");
  }

  function currentTimestamp() {
    try {
      return new Date().toLocaleString();
    } catch (error) {
      return String(new Date());
    }
  }

  function defaultsFromRuntime() {
    var runtime = global.BlockWriteAILetterHeadSettings || global.BlockWriteAILetterheadSettings || {};
    return {
      companyName: runtime.companyName || runtime.company_name || "",
      address: runtime.address || "",
      addressLine1: runtime.addressLine1 || runtime.address_line1 || "",
      addressLine2: runtime.addressLine2 || runtime.address_line2 || "",
      city: runtime.city || "",
      state: runtime.state || "",
      country: runtime.country || "",
      zipCode: runtime.zipCode || runtime.zip_code || "",
      email: runtime.email || runtime.email_address || "",
      mobile: runtime.mobile || runtime.mobile_number || "",
      logoUrl: runtime.logoUrlAbsolute || runtime.logo_url_absolute || runtime.logoUrl || runtime.logo_url || "",
      watermarkUrl: runtime.watermarkUrlAbsolute || runtime.watermark_url_absolute || runtime.watermarkUrl || runtime.watermark_url || ""
    };
  }

  function hasRuntimeDefaults() {
    var defaults = defaultsFromRuntime();
    return !!(defaults.companyName || defaults.address || defaults.addressLine1 || defaults.addressLine2 || defaults.city || defaults.state || defaults.country || defaults.zipCode || defaults.email || defaults.mobile || defaults.logoUrl || defaults.watermarkUrl);
  }

  function platformAssetBase() {
    var settings = global.BlockWriteAILetterHeadSettings || global.BlockWriteAILetterheadSettings || {};
    var base = settings.asset_base_url || settings.assetBaseUrl || global.BlockWriteAILetterHeadAssetBase || global.BlockWriteAIPlatformAssetBase || global.BlockWriteAIPlatformBaseUrl || "";
    if (base) return String(base).replace(/\/+$/, "") + "/";
    return "https://blockwriteai.in/";
  }

  function normalizePlatformUploadUrl(url) {
    url = String(url || "").trim();
    if (!url) return "";
    var match = url.match(/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?\/blockwriteai-platform\/(uploads\/letterhead\/.+)$/i);
    if (match) return platformAssetBase() + match[1].replace(/^\/+/, "");
    match = url.match(/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?\/(uploads\/letterhead\/.+)$/i);
    if (match) return platformAssetBase() + match[1].replace(/^\/+/, "");
    match = url.match(/^\/blockwriteai-platform\/(uploads\/letterhead\/.+)$/i);
    if (match) return platformAssetBase() + match[1].replace(/^\/+/, "");
    return url;
  }

  function resolveAssetUrl(url) {
    url = normalizePlatformUploadUrl(url);
    if (!url) return "";
    if (/^(https?:|data:|blob:|file:)/i.test(url)) return url;
    if (url.charAt(0) === "/") return platformAssetBase() + url.replace(/^\/+/, "");
    if (/^uploads\//i.test(url)) return platformAssetBase() + url.replace(/^\/+/, "");
    if (global.location) {
      try {
        return new URL(url, global.location.href).href;
      } catch (error) {}
    }
    return url;
  }

  function normalizeData(data) {
    var defaults = defaultsFromRuntime();
    data = data || {};
    var locked = hasRuntimeDefaults();
    var addressLine1 = locked ? defaults.addressLine1 : valueAny(data, "addressLine1", "address_line1", defaults.addressLine1);
    var addressLine2 = locked ? defaults.addressLine2 : valueAny(data, "addressLine2", "address_line2", defaults.addressLine2);
    var city = locked ? defaults.city : value(data, "city", defaults.city);
    var state = locked ? defaults.state : value(data, "state", defaults.state);
    var country = locked ? defaults.country : value(data, "country", defaults.country);
    var zipCode = locked ? defaults.zipCode : valueAny(data, "zipCode", "zip_code", defaults.zipCode);
    return {
      companyName: locked ? defaults.companyName : value(data, "companyName", defaults.companyName),
      address: locked ? defaults.address : value(data, "address", defaults.address),
      addressLine1: addressLine1,
      address_line1: addressLine1,
      addressLine2: addressLine2,
      address_line2: addressLine2,
      city: city,
      state: state,
      country: country,
      zipCode: zipCode,
      zip_code: zipCode,
      email: locked ? defaults.email : value(data, "email", defaults.email),
      mobile: locked ? defaults.mobile : value(data, "mobile", defaults.mobile),
      logoUrl: resolveAssetUrl(locked ? defaults.logoUrl : value(data, "logoUrl", defaults.logoUrl)),
      watermarkUrl: resolveAssetUrl(locked ? defaults.watermarkUrl : value(data, "watermarkUrl", defaults.watermarkUrl)),
      timestamp: currentTimestamp(),
      blocks: Array.isArray(data.blocks) && data.blocks.length ? data.blocks : [{ type: "paragraph", data: { text: "" } }]
    };
  }

  function addressLines(data) {
    var lines = [];
    var locality = [data.city, data.state, data.country, data.zipCode || data.zip_code].filter(Boolean).join(", ");
    if (data.addressLine1 || data.address_line1) lines.push(data.addressLine1 || data.address_line1);
    if (data.addressLine2 || data.address_line2) lines.push(data.addressLine2 || data.address_line2);
    if (locality) lines.push(locality);
    return lines.length ? lines : (data.address ? [data.address] : []);
  }

  function renderAddressLines(data) {
    return addressLines(data).map(function (line) {
      return "<span>" + esc(line) + "</span>";
    }).join("");
  }

  function letterheadHtml(data, helpers) {
    data = normalizeData(data);
    var renderBlock = helpers && helpers.renderBlock;
    var body = data.blocks.map(function (block) {
      return typeof renderBlock === "function"
        ? renderBlock(block)
        : '<p>' + inline(block && block.data ? block.data.text || "" : "") + "</p>";
    }).join("\n");
    return '<section class="rbe-output-letterhead-sheet">' +
      (data.watermarkUrl ? '<div class="rbe-output-letterhead-watermark"><img src="' + esc(data.watermarkUrl) + '" alt=""></div>' : "") +
      '<header class="rbe-output-letterhead-head"><div class="rbe-output-letterhead-company"><strong>' + esc(data.companyName || "Company Name") + "</strong>" +
      renderAddressLines(data) +
      (data.email ? "<span>" + esc(data.email) + "</span>" : "") +
      (data.mobile ? "<span>" + esc(data.mobile) + "</span>" : "") +
      '</div><div class="rbe-output-letterhead-logo-cell">' + (data.logoUrl ? '<img class="rbe-output-letterhead-logo" src="' + esc(data.logoUrl) + '" alt="' + esc(data.companyName || "Company") + ' logo">' : "") + "</div></header>" +
      '<hr class="rbe-output-letterhead-rule"><main class="rbe-output-letterhead-body">' + body + "</main>" +
      '<hr class="rbe-output-letterhead-rule"><footer class="rbe-output-letterhead-foot"><span>Page <span class="rbe-output-letterhead-page-number">1</span></span><span class="rbe-output-letterhead-foot-center">' + esc(data.companyName || "Company Name") + '</span><span class="rbe-output-letterhead-foot-right">' + esc(data.timestamp || "") + "</span></footer></section>";
  }

  BlockWriteAI.registerTool("letterHead", {
    label: "AI Letter head",
    hint: "Premium A4 company letterhead",
    icon: "file-lines",
    premiumFeature: "letterhead",
    defaultData: normalizeData({}),
    render: function (body, data) {
      injectStyles();
      data = normalizeData(data);
      var editor = this;
      var wrap = el("div", "rbe-letterhead-editor");
      wrap.innerHTML =
        '<div class="rbe-letterhead-locked-details" aria-label="Letter head details">' +
        '<div><span>Company Name</span><strong>' + esc(data.companyName || "Company Name") + '</strong></div>' +
        '<div><span>Email</span><strong>' + esc(data.email || "-") + '</strong></div>' +
        '<div class="rbe-letterhead-locked-wide"><span>Address</span><strong>' + esc(data.address || "-") + '</strong></div>' +
        '<div><span>Mobile</span><strong>' + esc(data.mobile || "-") + '</strong></div>' +
        '<div><span>Logo</span><strong>' + esc(data.logoUrl ? "Uploaded" : "Not uploaded") + '</strong></div>' +
        '<div class="rbe-letterhead-locked-wide"><span>Watermark</span><strong>' + esc(data.watermarkUrl ? "Uploaded" : "Not uploaded") + '</strong></div>' +
        '<div class="rbe-letterhead-locked-wide"><span>Timestamp</span><strong>' + esc(data.timestamp) + '</strong></div>' +
        "</div>";
      var nestedCanvas = el("div", "rbe-letterhead-nested-canvas");
      data.blocks.forEach(function (child) {
        var type = child && child.type ? child.type : "paragraph";
        if (type === "letterHead" || !BlockWriteAI.getTool(type) && CHILD_TYPES.map(function (item) { return item[0]; }).indexOf(type) < 0) type = "paragraph";
        var nestedBlock = editor.createBlock(type, child.data || editor.defaultBlockData(type), child.id || uid("block"));
        nestedBlock.classList.add("rbe-nested-block");
        nestedCanvas.appendChild(nestedBlock);
      });
      wrap.appendChild(nestedCanvas);
      body.appendChild(wrap);
    },
    serialize: function (block) {
      var nestedCanvas = block.querySelector(".rbe-letterhead-nested-canvas");
      var data = normalizeData({});
      return {
        companyName: data.companyName,
        address: data.address,
        addressLine1: data.addressLine1,
        address_line1: data.address_line1,
        addressLine2: data.addressLine2,
        address_line2: data.address_line2,
        city: data.city,
        state: data.state,
        country: data.country,
        zipCode: data.zipCode,
        zip_code: data.zip_code,
        email: data.email,
        mobile: data.mobile,
        logoUrl: data.logoUrl,
        watermarkUrl: data.watermarkUrl,
        timestamp: data.timestamp,
        blocks: nestedCanvas ? Array.prototype.slice.call(nestedCanvas.children).map(this.serializeBlock.bind(this)) : []
      };
    },
    toHTML: function (data, helpers) {
      injectStyles();
      return letterheadHtml(data, helpers || {});
    },
    toMarkdown: function (data, helpers) {
      data = normalizeData(data);
      var text = helpers && helpers.text ? helpers.text : function (html) { return String(html || "").replace(/<[^>]+>/g, ""); };
      return "# " + data.companyName + "\n\n" + data.blocks.map(function (block) {
        return text(block && block.data ? block.data.text || "" : "");
      }).filter(Boolean).join("\n\n");
    }
  });
})(typeof window !== "undefined" ? window : this);
