document.addEventListener("DOMContentLoaded",()=>{let v=null;function A(t,a){v&&(v.remove(),v=null);let l=a.dataset.entityType||"",u=null;if(l||(t.startsWith("user_meta_")?l="user":t.startsWith("order_meta_")||t.startsWith("order_billing_")||t.startsWith("order_shipping_")?l="order":t.startsWith("product_meta_")&&(l="product")),!l)return;switch(l){case"user":u=R();break;case"order":u=W();break;case"product":u=D();break}const e=document.createElement("div");e.className="notifal-dynamic-keys-popup";const s=I(t),r=notifalTagsStrings?.ui?.available_keys||"Available Keys",c=notifalTagsStrings?.ui?.search_placeholder||"Search keys...",f=notifalTagsStrings?.ui?.loading||"Loading available keys...",d=notifalTagsStrings?.ui?.searching||"Searching...",g=notifalTagsStrings?.ui?.keys_tooltip||"Available keys are listed below. Click a key to copy and use it in your template.";notifalTagsStrings?.ui?.no_keys,notifalTagsStrings?.alerts?.error_loading;const w=notifalTagsStrings?.alerts?.error_searching||"Error searching keys. Please try again.";e.innerHTML=`
            <div class="notifal-popup-header">
                <div style="display: flex; align-items: center; gap: 6px;">
                    <h4 style="margin:0;">${r}${s?" for "+s:""}</h4>
                    <div class="notifal-tooltip-wrapper" tabindex="0">
                        <span class="notifal-tooltip-icon">
                            <span class="notifal-icon notifal-icon-question-circle"></span>
                        </span>
                        <div class="notifal-tooltip-box">
                            ${g}
                        </div>
                    </div>
                </div>
                <div class="notifal-popup-controls">
                    <button class="notifal-popup-move" title="Move popover" aria-label="Move popover">
                        <span class="notifal-icon notifal-icon-arrows-move"></span>
                    </button>
                    <button class="notifal-popup-close" title="Close popover" aria-label="Close popover">
                        <span class="notifal-icon notifal-icon-x-circle"></span>
                    </button>
                </div>
            </div>
            <div class="notifal-popup-search">
                <input type="text" placeholder="${c}" class="notifal-search-input">
            </div>
            <div class="notifal-popup-content">
                <div class="notifal-loading">${f}</div>
            </div>
        `,e.style.position="fixed",e.style.zIndex="999999",document.body.appendChild(e),v=e;const b=window.innerWidth,T=window.innerHeight,S=e.getBoundingClientRect();let C=(b-S.width)/2,x=(T-S.height)/2;C<0&&(C=10),x<0&&(x=10),C+S.width>b&&(C=b-S.width-10),x+S.height>T&&(x=T-S.height-10),e.style.left=C+"px",e.style.top=x+"px";const F=e.querySelector(".notifal-popup-close"),m=e.querySelector(".notifal-popup-move"),p=e.querySelector(".notifal-popup-header"),H=e.querySelector(".notifal-search-input"),k=e.querySelector(".notifal-popup-content"),$={top:e.style.top,left:e.style.left};let h=!1,B=0,U=0,Y=0,K=0;F.addEventListener("click",()=>{e.remove(),v=null}),p.addEventListener("mouseenter",()=>{if(!h){p.style.cursor="move",p.style.backgroundColor="#e9ecef",m.style.opacity="0";let i=p.querySelector(".notifal-drag-message");i||(i=document.createElement("span"),i.className="notifal-drag-message",i.textContent="Click and drag to move",i.style.cssText=`
                        position: absolute;
                        right: 80px;
                        top: 50%;
                        transform: translateY(-50%);
                        font-size: 11px;
                        color: #666;
                        background: rgba(255, 255, 255, 0.9);
                        padding: 2px 6px;
                        border-radius: 3px;
                        pointer-events: none;
                        opacity: 0;
                        transition: opacity 0.2s ease;
                    `,p.appendChild(i),setTimeout(()=>i.style.opacity="1",10))}}),p.addEventListener("mouseleave",()=>{if(!h){p.style.cursor="",p.style.backgroundColor="",m.style.opacity="1";const i=p.querySelector(".notifal-drag-message");i&&(i.style.opacity="0",setTimeout(()=>i.remove(),200))}}),p.addEventListener("mousedown",i=>{if(i.target.closest(".notifal-popup-controls")||i.target.closest(".notifal-tooltip-wrapper"))return;i.preventDefault(),h=!0,B=i.clientX,U=i.clientY,Y=parseInt(e.style.left)||0,K=parseInt(e.style.top)||0,e.classList.add("notifal-popup-dragging"),document.body.style.cursor="move",p.style.backgroundColor="var(--notifal-primary)",p.style.color="#fff";const y=p.querySelector(".notifal-drag-message");y&&y.remove();const _=P=>{if(!h)return;const O=P.clientX-B,L=P.clientY-U;let E=Y+O,q=K+L;const M=e.getBoundingClientRect(),V=window.innerWidth,z=window.innerHeight;E<0&&(E=0),q<0&&(q=0),E+M.width>V&&(E=V-M.width),q+M.height>z&&(q=z-M.height),e.style.left=E+"px",e.style.top=q+"px"},X=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",X),h=!1,e.classList.remove("notifal-popup-dragging"),document.body.style.cursor="",p.style.backgroundColor="",p.style.color="",m.classList.remove("notifal-popup-move-active")};document.addEventListener("mousemove",_),document.addEventListener("mouseup",X)}),m.addEventListener("click",()=>{h&&(h=!1,e.style.top=$.top,e.style.left=$.left,e.classList.remove("notifal-popup-dragging"),document.body.style.cursor="",m.classList.remove("notifal-popup-move-active"),m.title="Move popover",p.style.backgroundColor="",p.style.color="")}),m.addEventListener("keydown",i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),m.click())});let N=[];n(l,u,t,k,function(i,y){y&&(N=i,o(N,t,k))});let j=null;H.oninput=function(i){const y=i.target.value.trim();if(j&&clearTimeout(j),y.length===0){o(N,t,k);return}k.innerHTML=`<div class="notifal-loading">${d}</div>`,j=setTimeout(()=>{if(H.value.trim()!==y)return;const _=window.wpApiSettings&&window.wpApiSettings.nonce||"",P=`${window.wpApiSettings&&window.wpApiSettings.root||`${window.location.origin}/wp-json`}notifal/v1/dynamic-keys?type=${l}&search=${encodeURIComponent(y)}`;fetch(P,{method:"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":_},credentials:"same-origin"}).then(L=>L.json()).then(L=>{H.value.trim()===y&&o(L,t,k)}).catch(L=>{console.error("Error searching dynamic keys:",L),k.innerHTML=`<div class="notifal-error">${w}</div>`})},400)},document.addEventListener("click",function i(y){!e.contains(y.target)&&!a.contains(y.target)&&(e.remove(),v=null,document.removeEventListener("click",i))}),document.addEventListener("keydown",function(y){e.contains(document.activeElement)&&y.key==="Escape"&&(h?(h=!1,e.style.top=$.top,e.style.left=$.left,e.classList.remove("notifal-popup-dragging"),document.body.style.cursor="",m.classList.remove("notifal-popup-move-active"),m.title="Move popover"):(e.remove(),v=null))})}function I(t){const a=t.replace(/^{|}$/g,"");return a.startsWith("user_meta_")?"user meta":a.startsWith("order_meta_")?"order meta":a.startsWith("product_meta_")?"product meta":""}function R(){return 0}function W(){const t=new URLSearchParams(window.location.search);return t.get("post")||t.get("order_id")||0}function D(){const t=new URLSearchParams(window.location.search);return t.get("post")||t.get("product_id")||0}function n(t,a,l,u,e){const s=window.wpApiSettings&&window.wpApiSettings.nonce||"",c=`${window.wpApiSettings&&window.wpApiSettings.root||`${window.location.origin}/wp-json`}notifal/v1/dynamic-keys?type=${t}`;fetch(c,{method:"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":s},credentials:"same-origin"}).then(d=>d.json()).then(d=>{e&&e(d,!0)}).catch(d=>{console.error("Error loading dynamic keys:",d),u.innerHTML=`<div class="notifal-error">${errorLoading}</div>`})}function o(t,a,l,u){if(!t||t.length===0){l.innerHTML=`<div class="notifal-no-keys">${noKeysLabel}</div>`;return}const e=t.map(s=>{const r=a.replace("{key}",s);return`<div class="notifal-key-item" data-tag="${r}">
                <span class="notifal-key-name">${s}</span>
                <span class="notifal-key-preview">${r}</span>
            </div>`}).join("");l.innerHTML=e,l.querySelectorAll(".notifal-key-item").forEach(s=>{s.addEventListener("click",()=>{const r=s.dataset.tag;if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(r);else{const c=document.createElement("textarea");c.value=r,c.style.position="fixed",c.style.opacity="0",document.body.appendChild(c),c.focus(),c.select();try{document.execCommand("copy")}catch{}document.body.removeChild(c)}s.classList.add("copied"),setTimeout(()=>{s.classList.remove("copied")},1500)})})}window.createDynamicKeysPopup=A});document.addEventListener("DOMContentLoaded",()=>{function v(n){navigator.clipboard&&navigator.clipboard.writeText?navigator.clipboard.writeText(n).catch(()=>{A(n)}):A(n)}function A(n){const o=document.createElement("textarea");o.value=n,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select();try{document.execCommand("copy")}catch(t){console.error("Fallback copy exception:",t)}document.body.removeChild(o)}document.addEventListener("input",function(n){n.target.classList.contains("notifal-search-input")&&I(n.target)}),document.addEventListener("click",function(n){if(n.target.classList.contains("notifal-category-tab")||n.target.closest(".notifal-category-tab")){const o=n.target.classList.contains("notifal-category-tab")?n.target:n.target.closest(".notifal-category-tab");R(o)}}),document.addEventListener("click",function(n){const o=n.target.closest(".notifal-tag");if(o){const t=o.querySelector(".notifal-tag-text");if(!t)return;const a=t.dataset.originalText||t.textContent.replace(/ - Copied$/,"").trim();t.dataset.originalText||(t.dataset.originalText=a),o.classList.contains("notifal-tag-dynamic")?(n.preventDefault(),n.stopPropagation(),typeof createDynamicKeysPopup=="function"&&createDynamicKeysPopup(a,o)):(v(a),o.classList.add("copied"),t.textContent=a+" - Copied",setTimeout(()=>{o.classList.remove("copied"),t.textContent=a},1500))}});function I(n){const o=n.value.toLowerCase().trim(),t=n.id,a=document.querySelector(`[data-search-input="${t}"]`);if(!a){console.warn("Notifal Tags: Could not find container for search input",t);return}const l=a.querySelectorAll(".notifal-tag"),u=a.querySelectorAll(".notifal-tags-category"),e=a.querySelector(".notifal-no-results");let s=0;l.forEach(r=>{const c=r.dataset.tagText||"",f=r.dataset.label||"",d=!o||c.toLowerCase().includes(o)||f.toLowerCase().includes(o);r.style.display=d?"inline-block":"none",d&&s++}),u.forEach(r=>{const c=r.querySelectorAll(".notifal-tag"),f=Array.from(c).some(d=>d.style.display!=="none");r.style.display=f?"block":"none"}),e&&(e.style.display=s===0&&o?"block":"none"),W(a,o)}function R(n){const o=n.closest(".notifal-category-tabs")?.dataset.container,t=document.getElementById("notifal-tags-"+o),a=n.dataset.category,l=n.closest(".notifal-category-tabs").querySelectorAll(".notifal-category-tab");if(!t){console.warn("Notifal Tags: Could not find container for category tab",o);return}l.forEach(r=>r.classList.remove("active")),n.classList.add("active");const u=t.querySelectorAll(".notifal-tags-category"),e=document.getElementById("notifal-search-"+o),s=e?e.value.toLowerCase().trim():"";u.forEach(r=>{const c=r.dataset.category;let f=!1;if(a==="all"){const d=r.querySelectorAll(".notifal-tag");f=Array.from(d).some(g=>{const w=g.dataset.tagText||"",b=g.dataset.label||"";return!s||w.toLowerCase().includes(s)||b.toLowerCase().includes(s)})}else if(f=c===a,f&&s){const d=r.querySelectorAll(".notifal-tag");d.forEach(g=>{const w=g.dataset.tagText||"",b=g.dataset.label||"",T=w.toLowerCase().includes(s)||b.toLowerCase().includes(s);g.style.display=T?"inline-block":"none"}),f=Array.from(d).some(g=>g.style.display!=="none")}r.style.display=f?"block":"none"}),D(t,s)}function W(n,o){const t=n.id.replace("notifal-tags-",""),a=document.querySelector(`[data-container="${t}"]`);if(!a){console.warn("Notifal Tags: Could not find tabs container for",t);return}a.querySelectorAll(".notifal-category-tab").forEach(u=>{const e=u.dataset.category;let s=0;if(e==="all")s=n.querySelectorAll('.notifal-tag[style*="display: inline-block"], .notifal-tag:not([style*="display"])').length;else{const c=n.querySelector(`.notifal-tags-category[data-category="${e}"]`);c&&c.querySelectorAll(".notifal-tag").forEach(d=>{const g=d.dataset.tagText||"",w=d.dataset.label||"";(!o||g.toLowerCase().includes(o)||w.toLowerCase().includes(o))&&s++})}const r=u.querySelector(".notifal-category-count");r&&(r.textContent=`(${s})`)})}function D(n,o){const t=n.querySelector(".notifal-no-results");if(!t)return;const l=n.querySelectorAll('.notifal-tag[style*="display: inline-block"], .notifal-tag:not([style*="display"])').length>0;t.style.display=!l&&o?"block":"none"}});
