"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const E=".rte-content, .editora-content",te='[data-theme="dark"], .dark, .editora-theme-dark',re={title:"Insert Merge Tag",searchPlaceholder:"Search merge tags...",emptyStateText:"No merge tags found",cancelText:"Cancel",insertText:"Insert",showPreview:!0};function ne(){return[{id:"USER",name:"User",tags:[{key:"first_name",label:"First Name",category:"User",preview:"John"},{key:"last_name",label:"Last Name",category:"User",preview:"Doe"},{key:"email",label:"Email",category:"User",preview:"john@example.com"},{key:"phone",label:"Phone",category:"User",preview:"+1-555-1234"},{key:"full_name",label:"Full Name",category:"User",preview:"John Doe"},{key:"username",label:"Username",category:"User",preview:"johndoe"}]},{id:"COMPANY",name:"Company",tags:[{key:"company_name",label:"Company Name",category:"Company",preview:"Acme Corp"},{key:"company_address",label:"Company Address",category:"Company",preview:"123 Main St"},{key:"company_phone",label:"Company Phone",category:"Company",preview:"+1-555-0000"},{key:"company_email",label:"Company Email",category:"Company",preview:"info@acme.com"}]},{id:"DATE",name:"Date",tags:[{key:"today",label:"Today",category:"Date",preview:new Date().toLocaleDateString()},{key:"tomorrow",label:"Tomorrow",category:"Date",preview:new Date(Date.now()+864e5).toLocaleDateString()},{key:"next_week",label:"Next Week",category:"Date",preview:new Date(Date.now()+6048e5).toLocaleDateString()}]},{id:"CUSTOM",name:"Custom",tags:[]}]}function R(t,r){return t.trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||`CATEGORY_${r+1}`}function ae(t,r){return(t.key||t.value||t.label).trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||`tag_${r+1}`}function oe(t){const r=(()=>{if(Array.isArray(t?.categories)&&t.categories.length>0)return t.categories;if(Array.isArray(t?.tags)&&t.tags.length>0){const c=new Map;return t.tags.forEach(d=>{const g=(d.category||"Custom").trim()||"Custom",i=c.get(g);i?i.push(d):c.set(g,[d])}),Array.from(c.entries()).map(([d,g],i)=>({id:R(d,i),name:d,tags:g}))}return ne()})(),e={},n=[];if(r.forEach((c,d)=>{const g=R(c.id||c.name,d);n.push(g),e[g]={name:c.name,tags:(Array.isArray(c.tags)?c.tags:[]).map((i,b)=>{const u=ae(i,b),f=(i.category||c.name).trim()||c.name;return{...i,key:u,category:f,categoryKey:g,searchIndex:`${i.label} ${u} ${f} ${i.description??""} ${i.value??""}`.toLowerCase()}})}}),n.length===0){const c="CUSTOM";n.push(c),e[c]={name:"Custom",tags:[]}}const a=t?.defaultCategory?R(t.defaultCategory,0):null,l=a&&n.includes(a)?a:n[0];return{categoriesByKey:e,categoryKeys:n,defaultCategory:l}}function le(t){const r=t?.tokenTemplate;return typeof r=="function"?e=>{const n=r(e);return typeof n=="string"&&n.trim()?n:e.value?.trim()||`{{ ${e.label} }}`}:typeof r=="string"&&r.trim()?e=>r.replace(/\{key\}/gi,e.key).replace(/\{label\}/gi,e.label).replace(/\{category\}/gi,e.category).replace(/\{value\}/gi,e.value??""):e=>e.value?.trim()||`{{ ${e.label} }}`}function ce(t){return{catalog:oe(t),dialog:{...re,...t?.dialog||{}},formatToken:le(t)}}let j=!1,H=!1,L=null,S=null,w=null,q=!1,y=null;function X(t,r){if(r===t.innerHTML)return;const e=window.execEditorCommand||window.executeEditorCommand;if(typeof e=="function")try{e("recordDomTransaction",t,r,t.innerHTML)}catch{}}function _(){if(j||typeof document>"u")return;j=!0;const t=document.createElement("style");t.id="merge-tag-plugin-styles",t.textContent=`
    .rte-merge-tag-overlay {
      --rte-mt-overlay-bg: rgba(15, 23, 36, 0.56);
      --rte-mt-dialog-bg: #ffffff;
      --rte-mt-dialog-text: #101828;
      --rte-mt-border: #d6dbe4;
      --rte-mt-subtle-bg: #f7f9fc;
      --rte-mt-subtle-hover: #eef2f7;
      --rte-mt-muted-text: #5f6b7d;
      --rte-mt-accent: #1976d2;
      --rte-mt-accent-strong: #1565c0;
      position: fixed;
      inset: 0;
      background-color: var(--rte-mt-overlay-bg);
      backdrop-filter: blur(2px);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 10000;
      padding: 16px;
      box-sizing: border-box;
    }

    .rte-merge-tag-overlay.rte-ui-theme-dark {
      --rte-mt-overlay-bg: rgba(2, 8, 20, 0.72);
      --rte-mt-dialog-bg: #202938;
      --rte-mt-dialog-text: #e8effc;
      --rte-mt-border: #49566c;
      --rte-mt-subtle-bg: #2a3444;
      --rte-mt-subtle-hover: #344256;
      --rte-mt-muted-text: #a5b1c5;
      --rte-mt-accent: #58a6ff;
      --rte-mt-accent-strong: #4598f4;
    }

    .rte-merge-tag-dialog {
      background: var(--rte-mt-dialog-bg);
      color: var(--rte-mt-dialog-text);
      border: 1px solid var(--rte-mt-border);
      border-radius: 12px;
      box-shadow: 0 24px 48px rgba(10, 15, 24, 0.28);
      width: 500px;
      max-width: 90vw;
      max-height: 80vh;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .rte-merge-tag-header { padding: 16px; border-bottom: 1px solid var(--rte-mt-border); display:flex; justify-content:space-between; align-items:center; }
    .rte-merge-tag-body {
      padding: 16px;
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .rte-merge-tag-input {
      width:100%;
      padding:11px 12px;
      border:1px solid var(--rte-mt-border);
      border-radius:6px;
      background:var(--rte-mt-subtle-bg);
      color:var(--rte-mt-dialog-text);
      font-size:14px;
      line-height:1.45;
      box-sizing:border-box;
    }
    .rte-merge-tag-tabs { display:flex; flex-wrap: wrap; gap:8px; margin: 12px 0; }
    .rte-merge-tag-tab { padding:8px 12px; background:none; border:none; cursor:pointer; color:var(--rte-mt-muted-text); border-bottom:3px solid transparent; }
    .rte-merge-tag-tab.active { color:var(--rte-mt-accent); border-bottom-color:var(--rte-mt-accent); }
    .rte-merge-tag-list {
      border:1px solid var(--rte-mt-border);
      border-radius:4px;
      flex: 1;
      min-height: 180px;
      max-height: 300px;
      overflow-y:auto;
      overflow-x:hidden;
      margin-bottom:12px;
      background:var(--rte-mt-subtle-bg);
    }
    .rte-merge-tag-item {
      padding:8px 12px;
      border-bottom:1px solid var(--rte-mt-border);
      cursor:pointer;
      transition:background-color 0.16s;
      color:var(--rte-mt-dialog-text);
      overflow-wrap:anywhere;
      word-break:break-word;
    }
    .rte-merge-tag-item:last-child { border-bottom: none; }
    .rte-merge-tag-item.selected, .rte-merge-tag-item:hover { background-color:var(--rte-mt-subtle-hover); }
    .rte-merge-tag-item-label { font-weight: 600; }
    .rte-merge-tag-item-preview { font-size: 12px; color: var(--rte-mt-muted-text); margin-top: 2px; overflow-wrap:anywhere; word-break:break-word; }
    .rte-merge-tag-empty { padding: 24px; text-align: center; color: var(--rte-mt-muted-text); }
    .rte-merge-tag-preview { padding:8px; background:var(--rte-mt-subtle-bg); border-radius:4px; font-family:monospace; font-size:12px; color:var(--rte-mt-dialog-text); overflow-wrap:anywhere; word-break:break-word; }
    .rte-merge-tag-footer { padding:12px 16px; border-top:1px solid var(--rte-mt-border); display:flex; gap:8px; justify-content:flex-end; background:var(--rte-mt-subtle-bg); }
    .rte-merge-tag-btn-primary { padding:8px 16px; border:none; border-radius:4px; background:var(--rte-mt-accent); color:#fff; cursor:pointer; }
    .rte-merge-tag-btn-primary:hover { background: var(--rte-mt-accent-strong); }
    .rte-merge-tag-btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
    .rte-merge-tag-btn-secondary { padding:8px 16px; border:1px solid var(--rte-mt-border); border-radius:4px; background:var(--rte-mt-subtle-bg); color:var(--rte-mt-dialog-text); cursor:pointer; }

    .rte-merge-tag {
      display: inline-flex;
      align-items: center;
      white-space: nowrap;
      user-select: none;
      background-color: #e3f2fd;
      border: 1px solid #bbdefb;
      border-radius: 3px;
      padding: 1px 6px;
      margin: 0 2px;
      color: #1976d2;
      font-weight: 600;
      line-height: 1.3;
    }

    .rte-merge-tag.rte-merge-tag-selected {
      outline: 2px solid #2563eb;
      outline-offset: 2px;
      box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.18);
    }

    :is([data-theme="dark"], .dark, .editora-theme-dark) .rte-merge-tag {
      background: #223247;
      border-color: #3f5f84;
      color: #8dc4ff;
    }
  `,document.head.appendChild(t)}function W(){H||typeof document>"u"||(H=!0,document.addEventListener("focusin",t=>{const e=t.target?.closest(E);e&&(L=e)}),document.addEventListener("selectionchange",()=>{const t=Z();t&&(L=t)}))}function Z(){const t=window.getSelection();if(!t||t.rangeCount===0)return null;const e=t.getRangeAt(0).startContainer;return(e.nodeType===Node.ELEMENT_NODE?e:e.parentElement)?.closest(E)||null}function Q(){const t=Z();if(t)return t;const e=document.activeElement?.closest(E);return e||(L?.isConnected?L:document.querySelector(E))}function O(){y&&(y.classList.remove("rte-merge-tag-selected"),y.removeAttribute("data-rte-selected-object"),y=null)}function ie(t){y!==t&&(O(),y=t,t.classList.add("rte-merge-tag-selected"),t.setAttribute("data-rte-selected-object","true")),se(t)}function se(t){const r=t.parentNode;if(!r)return;const e=window.getSelection();if(!e)return;const n=document.createRange(),l=Array.from(r.childNodes).indexOf(t);l<0||(n.setStart(r,l),n.setEnd(r,l+1),e.removeAllRanges(),e.addRange(n))}function V(t,r){t instanceof Text&&t.data.length!==0&&(r?(t.data.startsWith(" ")||t.data.startsWith(" "))&&t.deleteData(0,1):(t.data.endsWith(" ")||t.data.endsWith(" "))&&t.deleteData(t.data.length-1,1),t.data.length===0&&t.parentNode?.removeChild(t))}function G(t,r){const e=window.getSelection();if(!e)return;const n=document.createRange(),a=Math.max(0,Math.min(r,t.childNodes.length));n.setStart(t,a),n.collapse(!0),e.removeAllRanges(),e.addRange(n)}function de(t,r){const e=t.closest(E),n=e?.innerHTML??"",a=t.parentNode;if(!a)return!1;const c=Array.from(a.childNodes).indexOf(t);if(c<0)return!1;const d=t.previousSibling,g=t.nextSibling;return a.removeChild(t),y===t&&(y=null),r==="Backspace"?(V(g,!0),G(a,c)):(V(d,!1),G(a,c)),e&&(X(e,n),e.dispatchEvent(new Event("input",{bubbles:!0}))),!0}function ge(t){if(t.collapsed||!(t.startContainer instanceof HTMLElement||t.startContainer instanceof Text)||t.startContainer!==t.endContainer||t.endOffset!==t.startOffset+1)return null;const r=t.startContainer;if(!(r instanceof Element||r instanceof DocumentFragment))return null;const e=r.childNodes[t.startOffset];return e instanceof HTMLElement&&e.classList.contains("rte-merge-tag")?e:null}function me(t,r){if(!t.collapsed)return null;const{startContainer:e,startOffset:n}=t,a=l=>l instanceof HTMLElement&&l.classList.contains("rte-merge-tag")?l:null;if(e.nodeType===Node.ELEMENT_NODE){const l=e;return r==="Backspace"&&n>0?a(l.childNodes[n-1]||null):r==="Delete"?a(l.childNodes[n]||null):null}if(e.nodeType===Node.TEXT_NODE){const l=e;return r==="Backspace"?n===0?a(l.previousSibling):n===1&&(l.data[0]===" "||l.data[0]===" ")&&l.previousSibling instanceof HTMLElement&&l.previousSibling.classList.contains("rte-merge-tag")?l.previousSibling:null:n===l.data.length?a(l.nextSibling):null}return null}function J(){q||typeof document>"u"||(q=!0,document.addEventListener("pointerdown",t=>{const e=t.target?.closest(".rte-merge-tag");if(!e){t.target?.closest?.(".rte-merge-tag-overlay")||O();return}const n=e.closest(E);n&&(t.preventDefault(),t.stopPropagation(),n.focus({preventScroll:!0}),ie(e))},!0),document.addEventListener("keydown",t=>{if(t.key==="Escape"&&y){O();return}if(t.key!=="Backspace"&&t.key!=="Delete")return;const r=window.getSelection();if(!r||r.rangeCount===0)return;const e=r.getRangeAt(0),n=Q();if(!n||!n.contains(e.commonAncestorContainer))return;let a=y?.isConnected?y:null;a&&!n.contains(a)&&(a=null),a||(a=ge(e)),a||(a=me(e,t.key)),a&&(t.preventDefault(),t.stopPropagation(),de(a,t.key))}))}function ue(t){return t?!!t.closest(te):!1}function fe(){w&&(w(),w=null),S=null}function Y(t){const r=document.createRange();return r.selectNodeContents(t),r.collapse(!1),r}function pe(t,r){const e=window.getSelection(),n=r?r.cloneRange():Y(t),l=n.startContainer.isConnected&&n.endContainer.isConnected&&t.contains(n.commonAncestorContainer)?n:Y(t);return e&&(e.removeAllRanges(),e.addRange(l)),l}function be(t,r){const e=document.createElement("span");e.className="rte-merge-tag",e.setAttribute("contenteditable","false"),e.setAttribute("data-key",t.key),e.setAttribute("data-category",t.category),e.setAttribute("data-label",t.label),t.value&&e.setAttribute("data-value",t.value);const n=r(t);return e.setAttribute("data-token",n),e.setAttribute("aria-label",`Merge tag: ${t.label}`),e.textContent=n,e}function ye(t,r,e,n){const a=window.getSelection();if(!a)return!1;const l=t.innerHTML;t.focus({preventScroll:!0});const c=pe(t,r),g=(c.startContainer.nodeType===Node.ELEMENT_NODE?c.startContainer:c.startContainer.parentElement)?.closest(".rte-merge-tag");g&&t.contains(g)&&(c.setStartAfter(g),c.setEndAfter(g));try{c.deleteContents();const i=be(e,n),b=document.createTextNode(" "),u=document.createDocumentFragment();u.appendChild(i),u.appendChild(b),c.insertNode(u);const f=document.createRange();return f.setStartAfter(b),f.collapse(!0),a.removeAllRanges(),a.addRange(f),X(t,l),t.dispatchEvent(new Event("input",{bubbles:!0})),!0}catch(i){return console.error("Failed to insert merge tag:",i),!1}}function xe(t,r,e){const n=t.catalog.categoriesByKey[r]?.tags||[],a=e.trim().toLowerCase();return a?n.filter(l=>l.searchIndex.includes(a)):n}function ve(t,r){fe(),_();const e={category:r.catalog.defaultCategory,searchTerm:"",filteredTags:r.catalog.categoriesByKey[r.catalog.defaultCategory]?.tags||[],selectedIndex:0,savedRange:(()=>{const o=window.getSelection();if(!o||o.rangeCount===0)return null;const s=o.getRangeAt(0);return t.contains(s.commonAncestorContainer)?s.cloneRange():null})(),searchRaf:null},n=document.createElement("div");n.className="rte-merge-tag-overlay",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),ue(t)&&n.classList.add("rte-ui-theme-dark");const a=document.createElement("div");a.className="rte-merge-tag-dialog";const l=document.createElement("div");l.className="rte-merge-tag-header";const c=document.createElement("h2");c.style.margin="0",c.style.fontSize="18px",c.style.fontWeight="700",c.textContent=r.dialog.title;const d=document.createElement("button");d.className="rte-merge-tag-close",d.setAttribute("aria-label","Close"),d.style.background="none",d.style.border="none",d.style.color="inherit",d.style.cursor="pointer",d.style.fontSize="20px",d.textContent="✕",l.appendChild(c),l.appendChild(d);const g=document.createElement("div");g.className="rte-merge-tag-body";const i=document.createElement("input");i.type="text",i.className="rte-merge-tag-input",i.placeholder=r.dialog.searchPlaceholder,i.setAttribute("aria-label","Search merge tags");const b=document.createElement("div");b.className="rte-merge-tag-tabs",r.catalog.categoryKeys.forEach(o=>{const s=document.createElement("button");s.type="button",s.className="rte-merge-tag-tab",s.setAttribute("data-category",o),s.textContent=r.catalog.categoriesByKey[o]?.name||o,b.appendChild(s)});const u=document.createElement("div");u.className="rte-merge-tag-list";const f=document.createElement("div");f.className="rte-merge-tag-preview",g.appendChild(i),g.appendChild(b),g.appendChild(u),g.appendChild(f);const T=document.createElement("div");T.className="rte-merge-tag-footer";const h=document.createElement("button");h.type="button",h.className="rte-merge-tag-btn-secondary",h.textContent=r.dialog.cancelText;const x=document.createElement("button");x.type="button",x.className="rte-merge-tag-btn-primary",x.textContent=r.dialog.insertText,T.appendChild(h),T.appendChild(x),a.appendChild(l),a.appendChild(g),a.appendChild(T),n.appendChild(a),document.body.appendChild(n),S=n;const z=()=>{b.querySelectorAll(".rte-merge-tag-tab").forEach(s=>{const p=s.dataset.category===e.category;s.classList.toggle("active",p)})},A=()=>{if(e.filteredTags.length===0){e.selectedIndex=-1;return}e.selectedIndex<0&&(e.selectedIndex=0),e.selectedIndex>=e.filteredTags.length&&(e.selectedIndex=e.filteredTags.length-1)},F=()=>{if(!r.dialog.showPreview){f.style.display="none",x.disabled=e.filteredTags.length===0;return}A();const o=e.selectedIndex>=0?e.filteredTags[e.selectedIndex]:null;if(!o){f.style.display="none",x.disabled=!0;return}f.style.display="block",f.textContent=`Preview: ${r.formatToken(o)}`,x.disabled=!1},ee=()=>{if(e.selectedIndex<0)return;u.querySelector(`.rte-merge-tag-item[data-index="${e.selectedIndex}"]`)?.scrollIntoView({block:"nearest"})},k=()=>{u.querySelector(".rte-merge-tag-item.selected")?.classList.remove("selected"),e.selectedIndex>=0&&u.querySelector(`.rte-merge-tag-item[data-index="${e.selectedIndex}"]`)?.classList.add("selected"),F(),ee()},D=()=>{if(e.filteredTags=xe(r,e.category,e.searchTerm),e.filteredTags.length>0&&e.selectedIndex<0&&(e.selectedIndex=0),A(),u.innerHTML="",e.filteredTags.length===0){const s=document.createElement("div");s.className="rte-merge-tag-empty",s.textContent=r.dialog.emptyStateText,u.appendChild(s),F();return}const o=document.createDocumentFragment();e.filteredTags.forEach((s,p)=>{const m=document.createElement("div");m.className="rte-merge-tag-item",m.setAttribute("data-index",String(p)),m.classList.toggle("selected",p===e.selectedIndex);const M=document.createElement("div");if(M.className="rte-merge-tag-item-label",M.textContent=s.label,m.appendChild(M),s.preview){const I=document.createElement("div");I.className="rte-merge-tag-item-preview",I.textContent=s.preview,m.appendChild(I)}o.appendChild(m)}),u.appendChild(o),k()},P=()=>{e.searchRaf!==null&&cancelAnimationFrame(e.searchRaf),e.searchRaf=requestAnimationFrame(()=>{e.searchRaf=null,e.searchTerm=i.value,e.selectedIndex=0,D()})},v=()=>{e.searchRaf!==null&&(cancelAnimationFrame(e.searchRaf),e.searchRaf=null),n.remove(),S===n&&(S=null,w=null)},C=()=>{if(A(),e.selectedIndex<0)return;const o=e.filteredTags[e.selectedIndex];ye(t,e.savedRange,o,r.formatToken)&&v()},B=o=>{const p=o.target.closest(".rte-merge-tag-tab");if(!p)return;const m=p.dataset.category;!m||!r.catalog.categoriesByKey[m]||(e.category=m,e.searchTerm="",i.value="",e.selectedIndex=0,z(),D())},U=o=>{const p=o.target.closest(".rte-merge-tag-item");if(!p)return;const m=Number(p.dataset.index||"-1");Number.isNaN(m)||m<0||m>=e.filteredTags.length||(e.selectedIndex=m,k())},$=o=>{const p=o.target.closest(".rte-merge-tag-item");if(!p)return;const m=Number(p.dataset.index||"-1");Number.isNaN(m)||m<0||m>=e.filteredTags.length||(e.selectedIndex=m,C())},N=o=>{if(o.key==="Escape"){o.preventDefault(),v();return}if(o.key==="ArrowDown"){if(o.preventDefault(),e.filteredTags.length===0)return;e.selectedIndex=Math.min(e.filteredTags.length-1,e.selectedIndex+1),k();return}if(o.key==="ArrowUp"){if(o.preventDefault(),e.filteredTags.length===0)return;e.selectedIndex=Math.max(0,e.selectedIndex-1),k();return}o.key==="Enter"&&(o.preventDefault(),C())},K=o=>{o.target===n&&v()};b.addEventListener("click",B),u.addEventListener("click",U),u.addEventListener("dblclick",$),i.addEventListener("input",P),i.addEventListener("keydown",N),n.addEventListener("click",K),a.addEventListener("keydown",N),d?.addEventListener("click",v),h.addEventListener("click",v),x.addEventListener("click",C),w=()=>{b.removeEventListener("click",B),u.removeEventListener("click",U),u.removeEventListener("dblclick",$),i.removeEventListener("input",P),i.removeEventListener("keydown",N),n.removeEventListener("click",K),a.removeEventListener("keydown",N),d?.removeEventListener("click",v),h.removeEventListener("click",v),x.removeEventListener("click",C),e.searchRaf!==null&&(cancelAnimationFrame(e.searchRaf),e.searchRaf=null),n.remove()},z(),D(),setTimeout(()=>{i.focus()},0)}const he=t=>({name:"mergeTag",config:t,init:()=>{_(),W(),J()},toolbar:[{label:"Merge Tag",command:"insertMergeTag",icon:"{{ }}"}],commands:{insertMergeTag:()=>{_(),W(),J();const r=Q();return r?(ve(r,ce(t)),!0):!1}}});exports.MergeTagPlugin=he;
